【发布时间】:2015-04-09 22:23:20
【问题描述】:
我在下面有一个非常简单的 sn-p,我试图找出导致分段错误的原因。
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;
}
如果我删除包含在开始和结束注释中的块 - 我看不到 seg 错误。但我认为这会导致泄漏。
非常感谢任何帮助。
【问题讨论】:
-
您将
'a'分配给您已声明为字符指针的变量。换句话说,test[index] = 'a'用字符'a'替换了从堆中分配的指针。然后你尝试释放'a'(因为这是free(test[index])中test[index]的值),就好像它是一个分配的指针一样。那是个问题。我猜你的意思是,*test[index] = 'a'。 -
或
char *test1=(char*)malloc(sizeof(char) * size);..test1[index]='a';..free(test1); -
天啊...这就是问题所在 - 应该是 *test1[index]。非常感谢 BLUEPIXY
-
或
test1[index]='a';更改为test1[index][0]='a';
标签: c arrays segmentation-fault malloc free