Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with passing struct pointer by pthread_create

Tags:

c

pthreads

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?

like image 733
user482594 Avatar asked May 16 '26 10:05

user482594


1 Answers

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**.

like image 161
Mat Avatar answered May 19 '26 00:05

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!