cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
spark1001
Visitor
Visitor
672 Views
Registered: ‎04-13-2021

segmentation fault when using pthread_join()

Jump to solution

here is my code :

......
void* print1(void* data){
printf("1 \n");
}
.....
.....

pthread_t* t=(pthread_t*)malloc(sizeof(pthread_t));

pthread_create(&t[0],0,print1,NULL);
printf("****** after test create thread******* \n");
pthread_join(t[0],NULL);
printf("****** test pthread lib******* \n");
 
the result is :
2021-05-07 20-01-11 的屏幕截图.png
I create the thread successfully,but I can't use pthread_join.
what should I do?
0 Kudos
1 Solution

Accepted Solutions
gsmecher
Explorer
Explorer
627 Views
Registered: ‎01-21-2011

There is no bug in the code you've posted. That means either:

  • There's a problem in the runtime you're using (possible), or
  • There's a bug in the surrounding code you haven't included (seems mosts likely to me).

In order to figure out which is true, please paste a complete example here that exhibits the same segfault. If you don't want to share your code publicly, it's a great idea to trim your example down so it doesn't give away any secrets.

For reference, the following standalone C code is much like yours, and is leak- and error-free. (Don't forget, though, that malloc and pthread_create can return an error code!)

#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

void* print1(void *data) {
        printf("1\n");
        return NULL;
}

int main(void) {
        pthread_t *t = (pthread_t *)malloc(sizeof(pthread_t));

        pthread_create(t, 0, print1, NULL);
        pthread_join(*t, NULL);

        free(t);
        return 0;
}

cheers,
Graeme

View solution in original post

1 Reply
gsmecher
Explorer
Explorer
628 Views
Registered: ‎01-21-2011

There is no bug in the code you've posted. That means either:

  • There's a problem in the runtime you're using (possible), or
  • There's a bug in the surrounding code you haven't included (seems mosts likely to me).

In order to figure out which is true, please paste a complete example here that exhibits the same segfault. If you don't want to share your code publicly, it's a great idea to trim your example down so it doesn't give away any secrets.

For reference, the following standalone C code is much like yours, and is leak- and error-free. (Don't forget, though, that malloc and pthread_create can return an error code!)

#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

void* print1(void *data) {
        printf("1\n");
        return NULL;
}

int main(void) {
        pthread_t *t = (pthread_t *)malloc(sizeof(pthread_t));

        pthread_create(t, 0, print1, NULL);
        pthread_join(*t, NULL);

        free(t);
        return 0;
}

cheers,
Graeme

View solution in original post