I am getting Segmentation Fault for the following code which is weird cuz I don’t see where I am accessing un-initialized memory. I have tried to debug the code and found that this segmentation fault has something to do with *g inside thread procedure. Here is the code:
void *Func(void *arg);
int main()
{
pthread_t tid;
void *x;
pthread_create(&tid,NULL,Func,NULL);
pthread_join(tid,&x);
int i=*(int *)x;
printf("Data returned from the thread %d\n",i);
return 0;
}
void *Func(void *arg)
{
int *g;
int i=2,j=3;
printf("inside thread\n");
*g=i+j;
printf("%d\n",*g);
return g;
}
The problem is with the code below
gis an uninitialised pointer. When you dereference it, you are trying to write to an undefined location in memory. The effects of this are undefined but a seg fault is very likely.There are a number of ways you could address this, including
ggtowards some allocated memorygon the stack inmainand pass a pointer to it into your child thread