Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading