在下面的代码中,当我在主函数中打印
f->msg
时,数据能够正确打印。然而,如果我将mystruct *f传递给pthread_create
并尝试打印出msg的值,则会在receive_data
函数的第二行出现分段错误。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);
}
其他pthread的初始化代码未显示。
我该如何解决这个问题?
f->msg[0] = '\0';
是完全没有用的。 - Vinicius Kamakura