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?
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()
.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.