Problem with passing struct pointer by pthread_create
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
pthre开发者_运维百科ad_create(&worker,&attr,receive_data,&f);
}
Other initialization code for pthread is not shown.
How can I resolve this problem?
You're passing a pointer-to pointer-to mystruct
. Don't do that.
pthread_create(&worker, &attr, receive_data, f);
is enough. f
is already of type mystruct*
. &f
is of type mystruct**
.
精彩评论