我正在使用这样的东西来分配带有函数的内存(在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;
}
但是我遇到了段错误。这段代码有什么问题?
答案 0 :(得分:4)
在struct mystruct **x;
之后,变量x
未初始化。如你的程序在*x = NULL;
中所做的那样读取它是违法的。
你可能想写:
int main()
{
struct mystruct *x;
x = NULL;
myfunction(&x);
return 0;
}
但是不可能确定,因为你的程序没有做任何有意义的事情。
请注意,x = NULL;
无论如何都是不必要的:x
将在myfunction()
内初始化。
答案 1 :(得分:0)
你永远不会为底层指针创建任何存储空间,**
和对象存储但不存储*
......
struct mystruct **x,*y;
x = &y;
myfunction(x);
return 0;