[英]Getting seg fault when using malloc with double pointer
I'm using something like this to allocate memory with a function (in C) 我正在使用像这样的东西来分配带有函数的内存(在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;
在
struct mystruct **x;
, the variable x
is uninitialized. ,变量
x
尚未初始化。 It is illegal to read from it as your program does in *x = NULL;
像程序在
*x = NULL;
那样进行读取是非法的*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;
注意,
x = NULL;
is unnecessary anyway: x
will be initialized inside myfunction()
. 无论如何都是不必要的:
x
将在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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.