Alfred
Alfred

Reputation: 1663

Why it this code triggering a segmentation fault?

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

Answers (3)

simonc
simonc

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

  • allocate memory for g
  • point g towards some allocated memory
  • declare g on the stack in main and pass a pointer to it into your child thread

Upvotes: 3

Grijesh Chauhan
Grijesh Chauhan

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

codaddict
codaddict

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

Related Questions