zzzbbx
zzzbbx

Reputation: 10131

Getting seg fault when using malloc with double pointer

I'm using something like this to allocate memory with a function (in C)

void myfunction(struct mystruct** ss) {
    // some code
    *ss = malloc( 1024 * sizeof (struct mystruct) );
    // some code
}    
int main()
{
   struct mystruct **x;
   *x = NULL;
   myfunction(x);
   return 0;
}

but I'm getting seg fault. What is wrong with this code?

Upvotes: 1

Views: 114

Answers (2)

Grady Player
Grady Player

Reputation: 14549

you never make any storage for the underlying pointer, there is storage for the ** and the object but not the *...

struct mystruct **x,*y;
x = &y;
myfunction(x);
return 0;

Upvotes: 0

Pascal Cuoq
Pascal Cuoq

Reputation: 80276

After struct mystruct **x;, the variable x is uninitialized. It is illegal to read from it as your program does in *x = NULL;.

You may have wanted to write:

int main()
{
   struct mystruct *x;
   x = NULL;
   myfunction(&x);
   return 0;
}

But it is impossible to be sure, as your program does not do anything meaningful. Note that x = NULL; is unnecessary anyway: x will be initialized inside myfunction().

Upvotes: 4

Related Questions