views:

456

answers:

2

In the following code I get a segmentation fault:

Set *getpar() {...}

char function(...) 
{
   Set **S;
   *S = getpar(); /* Segmentation Fault */
   ...
}

But the bizarre thing is that with few changes there is no segmentation fault:

Set *getpar() {...}
...
char function(...) 
{
   Set *S;       // One less '*'
   S = getpar(); // One less '*'
   ...
}

As I know, if there is a 'Set **S' then *S is a pointer to a Set object, so if the second code works fine, why shouldn't the first? *S of the first code is equivalent to S of the second code, am I not right? How can I solve the problem?

+8  A: 

Set **S is not initized, but you dereference S in the next statement:

*S = whatever

Unless you get really, really unlucky and S is pointing to a memory location you can actually access, you're trying to dereference an invalid pointer.

You would need to allocate your pointer first:

Set **S;
S = (S**)calloc(sizeof(S*),1);
*S = getpar();

Or, alternatively (and preferable, I think):

Set *S;
Set **T = &S;

S = getpar();

/* whatever else */
Ben Collins
Thanks a lot! I spent hours on that thing.
Leif Ericson
A: 

**S is not initialized. Its pointing to nothing (garbage) and then you de-reference it in the next statement.

Aditya Sehgal