Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation Fault with pointer-to-pointer with C / Linux

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?

like image 325
Ori Popowski Avatar asked Sep 22 '26 16:09

Ori Popowski


1 Answers

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 */
like image 138
Ben Collins Avatar answered Sep 24 '26 08:09

Ben Collins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!