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

alk
  • 69,737
  • 10
  • 105
  • 255
  • 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. – WhozCraig Oct 05 '14 at 06:37

2 Answers2

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);
}
alk
  • 69,737
  • 10
  • 105
  • 255
alireza_fn
  • 884
  • 1
  • 8
  • 21
  • [You should not cast the result of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc), but otherwise a good answer. – IllusiveBrian Oct 05 '14 at 06:45
1

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

Cory Nelson
  • 29,236
  • 5
  • 72
  • 110