简体   繁体   中英

I get segmentation fault while making a simple pthreads program in C and I don't understand why

This simple code compiles fine but when I use pthread_join(t1, NULL) it returns segmentation fault (core dump)

int number = 0;

void* change_number(void *x){
    printf("helo from some thread\n");
        int num = *(int *)x;
        printf("%d\n", number);
        number += num;
    
        printf("a thread increased the variable by %d\n", num);
    }

int main(int argc, char* argv[])
{

        pthread_t t1;
        pthread_t t2;
        printf("1) SUccess code: %d\n", pthread_create(&t1, NULL, change_number, (void *) 5));
        printf("2) Success code: %d\n", pthread_create(&t2, NULL, change_number, (void *) 11));
        printf("%d\n",pthread_join(t1, NULL));
        printf("thread 1 finished\n");
        pthread_join(t2, NULL);

}

What is the issue here? I run this in a VM if it has any relevance

(void*)5 says to treat 5 as a pointer, where what you seem to want is a pointer to an int variable that contains 5.

As others have noted, your problem is in (void *) 5 , this is easily fixed:

int foo = 5, bar = 11;

printf("1) SUccess code: %d\n", pthread_create(&t1, NULL, change_number, (void *) &foo));
printf("2) Success code: %d\n", pthread_create(&t2, NULL, change_number, (void *) &bar));

As noted, you should make the foo and bar variables globals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM