【问题标题】:Dynamic 2D Array with realloc gives segmentation fault, but works with malloc具有 realloc 的动态 2D 数组会产生分段错误,但可与 malloc 一起使用
【发布时间】:2015-08-13 19:56:10
【问题描述】:

我的动态二维数组有问题。 与malloc 一起工作。使用realloc,它失败了。

这不起作用:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *const *argv) {

    unsigned ** gmatrix = NULL;
    int cap = 4;

    /*
    ...
    */

    gmatrix = realloc(gmatrix, 4 * sizeof(unsigned*));
    for(unsigned i = 0; i < cap; i++) {
        gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
    }
    // initialize:
    for(unsigned i = 0; i < cap; i++) {
        for(unsigned j =  0; j < cap; j++) {
            gmatrix[i][j] = 0;
        }
    }

}

但这确实:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *const *argv) {

    unsigned ** gmatrix = NULL;
    int cap = 4;

    /*
    ...
    */
    gmatrix = malloc(cap * sizeof(unsigned*));
    for(unsigned i = 0; i < cap; i++) {
        gmatrix[i] = malloc(cap* sizeof(unsigned));
    }
    for(unsigned i = 0; i < cap; i++) {
        for(unsigned j =  0; j < cap; j++) {
            gmatrix[i][j] = 0;
        }
    }

}

在第一个代码部分中,我收到了分段错误错误。为什么?

【问题讨论】:

  • 对我来说很好用!您确定这是生成段错误的代码吗?顺便说一句,您忘记释放两个程序中分配的内存。
  • 哦,行中有错误:gmatrix[i] = malloc(cap* sizeof(unsigned));它应该是 gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));
  • 现在更正了。
  • calloc 对于gmatrix[i] 会更好,以避免将条目归零。

标签: c multidimensional-array segmentation-fault malloc realloc


【解决方案1】:
gmatrix[i] = realloc(gmatrix, cap* sizeof(unsigned));

应该是

gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));

使用gmatrix 而不是gmatrix[i] 将导致Undefined Behavior 并且您遇到的分段错误是Undefined Behavior 的副作用之一。


编辑

您应该在第一个 malloc 之后将 gmatrix[i] 初始化为 NULL@MattMcNabb pointed out。所以在第一次调用realloc后使用以下内容:

for(unsigned i = 0; i < cap; i++) {
    gmatrix[i] = NULL;
    gmatrix[i] = realloc(gmatrix[i], cap* sizeof(unsigned));
}

【讨论】:

  • 非常感谢!我昨天花了 2 个小时。
  • 这也是一个错误,因为gmatrix[i] 在调用 realloc 之前未初始化(除非 OP 打算将“...”包括它的初始化)
  • @MattMcNabb ,我也想过。我认为第一个realloc 将每一行初始化为NULL。它没有,对吧?
  • 我应该循环使用NULL初始化所有gmatrix[i]吗?
  • @k2jj2k ,是的,但最好在“编辑”部分中的代码所示的同一循环中执行。
猜你喜欢
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
相关资源
最近更新 更多