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?
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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With