1
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>

pthread_t id1,id2;
struct arg{int a[2];}*p;

void *sum(void *args)
{
    struct arg *b=((struct arg*)args);
    printf("hello:%d%d",b->a[0],b->a[1]);
}

void *mul(void *args)
{
    struct arg *c=((struct arg*)args);
    printf("hi:%d%d",c->a[0],c->a[1]);
}

main()
{
    int err1,err2;
    p->a[0]=2;
    p->a[1]=3;
    err1=pthread_create(&id1,NULL,&sum,(void*)p);
    err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}

I am trying to pass data to threads using structure .....but i always gets a segmentation fault error....can anyone tell me what's wrong with my code..

1
  • Before assuming you're setting up threading incorrectly, consider that if you threw out the threading, and just invoked either sum or mul with p setup as you have it (or lack thereof as the case may be), you would likely get the same result (crash in a ball of flames). In short, you forgot (or never learned) how pointers work in C. Commented Oct 5, 2014 at 6:37

2 Answers 2

2

You are getting segmentation fault because you have not allocated memory for p; it tries to assign values to memory address 0 which leads to a segfault.

Try allocating memory with malloc:

main()
{
int err1,err2;
struct arg *p=(struct arg *)malloc(sizeof(struct arg));
p->a[0]=2;
p->a[1]=3;
err1=pthread_create(&id1,NULL,&sum,(void*)p);
err2=pthread_create(&id2,NULL,&mul,(void*)p);sleep(5);
}
Sign up to request clarification or add additional context in comments.

1 Comment

You should not cast the result of malloc, but otherwise a good answer.
1

You're getting a segfault because p is initialized to 0. You aren't assigning anything to it.

1 Comment

@alk being a global it is initialized to a null pointer as per C standard.

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.