【问题标题】:C - 2D Array malloc/free - Segmentation faultC - 2D 数组 malloc/free - 分段错误
【发布时间】: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


【解决方案1】:

我认为您的意思是取消引用 test1[index]。您的代码用“a”覆盖了已分配内存的地址,因此当它尝试释放内存时会出现错误,因为“a”不是有效地址。

test1[index]=(char*)malloc(sizeof(char));
*test1[index]='a';

这个也可以

test1[index][0]='a';

【讨论】:

    【解决方案2】:

    你开始很好:

    test1=(char**)malloc(sizeof(char*) * size);
        if (test1 != NULL) {
    

    你的循环不是:

            for (index = 0; index < size ; index++) {
                    test1[index]=(char*)malloc(sizeof(char));
                    test1[index]='a';
            }
    

    首先,你只为应该是一行字符的内容分配一个字节(因为你只有一个“大小”变量,我假设你希望你的二维数组是正方形的:2x2。所以你需要乘以这里的大小就像你在外循环中所做的那样。你不需要需要“sizeof(char)”,这只是输入“1”的冗长方式。

    但更糟糕的是,在分配的行太短之后,您会通过用字符覆盖指针来丢弃该内存(您应该在此处收到编译器警告)。这是等待发生的灾难和内存泄漏。

    你真正的意思是:

            for (index = 0; index < size ; index++) {
                    test1[index]=malloc(size);
                    test1[index][0]='a';
            }
    

    【讨论】:

      猜你喜欢
      • 2011-12-15
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多