我正在使用类似这样的函数来分配内存(在 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;
}
但我遇到了段错误。这段代码有什么问题?
最佳答案
在struct mystruct **x;
之后,变量x
未初始化。像您的程序在 *x = NULL;
中读取它是非法的。
你可能想写:
int main()
{
struct mystruct *x;
x = NULL;
myfunction(&x);
return 0;
}
但无法确定,因为您的程序没有做任何有意义的事情。
请注意 x = NULL;
无论如何都是不必要的:x
将在 myfunction()
中初始化。
关于c - 使用带双指针的 malloc 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23572910/