In the code below, when I print f->msg in the main function, the data prints out correctly. However, if I pass the mystruct *f in pthread_create and try to print out the msg value, I get a segmentation fault on the second line of the receive_data function.
typedef struct _mystruct{
char *msg;
} mystruct;
void *receive_data(void* vptr){
mystruct *f = (mystruct*)vptr;
printf("string is %s\n",mystruct->msg);
return NULL;
}
int main(){
mystruct *f = malloc(sizeof(mystruct));
f->msg = malloc(1000);
f->msg[0] = '\0';
strcpy(f->msg,"Hello World");
pthread_t worker;
printf("[%s]\n",f->msg);
// attr initialization is not shown
pthread_create(&worker,&attr,receive_data,&f);
}
Other initialization code for pthread is not shown.
How can I resolve this problem?
f->msg[0] = '\0';is completely useless in that code of yours