3

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?

2
  • f->msg[0] = '\0'; is completely useless in that code of yours Commented Jun 19, 2011 at 20:52
  • Yeah, I see that, in the actual code, I do strcat instead of strcpy which needs to locate '\0'. But, it was my mistake in this context. Commented Jun 19, 2011 at 21:40

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

Also OP's program almost surely terminates before it has a chance to print anything since it runs off the end of main...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.