C - 2D 数组 malloc/free - 段错误

标签 c arrays segmentation-fault malloc free

下面有一个非常简单的代码片段,我试图找出出现段错误的原因。

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/

相关文章:

python - 查找总和最接近给定数字的二维数组的路径

c - 在 C 中将 int 转换为 char 时出现段错误

将文件指针传递给方法时出现 C 段错误

c - 如何在没有段错误的情况下将双指针传递给函数 C 语言

c - 如何在 Visual Studio 中包含 header 和源文件文件夹

c - 在函数中调用时,数组被修改而不是 int

arrays - 尝试访问数组时不断出现访问冲突

c++ - 数组是指针吗?

c - 哦不,不是另一个 undefined reference 问题!

c - 如何在 c 中正确使用 scandir()?