3

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?

2 Answers 2

10

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 */
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! I spent hours on that thing.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.