使用带双指针的malloc时出现seg错误

时间:2014-05-09 19:55:18

标签: c pointers segmentation-fault

我正在使用这样的东西来分配带有函数的内存(在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;
}

但是我遇到了段错误。这段代码有什么问题?

2 个答案:

答案 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;