Reputation: 1663
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;
}
Upvotes: 2
Views: 116
Reputation: 42175
The problem is with the code below
int *g;
....
*g=i+j;
g
is 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
g
g
towards some allocated memoryg
on the stack in main
and pass a pointer to it into your child threadUpvotes: 3
Reputation: 58271
in int *g;
g is an address of location that is not allocated and you are trying to assigned on that location.
do like this:
int *g=calloc(1, sizeof(int)) ;
Also don't forget to free
memory.
Upvotes: 2
Reputation: 455020
You are doing:
int *g;
...
*g=i+j;
g
is an uninitialized pointer and you are trying to write to the location it is pointing to, which leads to undefined behavior.
Upvotes: 1