下面有一个非常简单的代码片段,我试图找出出现段错误的原因。
int main (int argc, char** argv)
{
const int size = 2;
char** test1 = NULL;
int index = 0;
test1=(char**)malloc(sizeof(char*) * size);
if (test1 != NULL)
{
for (index = 0; index < size ; index++)
{
test1[index]=(char*)malloc(sizeof(char));
test1[index]='a';
}
//Removing this block does not result in seg fault - start
for (index = 0 ; index < size ; index++)
{
free(test1[index]); //Seg. fault here
}
//Removing this block does not result in seg fault - end
free(test1);
}
return 0;
}
如果我删除开始和结束注释中包含的 block - 我看不到段错误。但我认为这会导致泄漏。
非常感谢任何帮助。
最佳答案
我认为您的意思是取消引用 test1[index]。您的代码用“a”覆盖已分配内存的地址,因此当它尝试释放内存时,它会出现错误,因为“a”不是有效地址。
test1[index]=(char*)malloc(sizeof(char));
*test1[index]='a';
这也有效
test1[index][0]='a';
关于C - 2D 数组 malloc/free - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29550093/