带有 realloc 的动态二维数组给出分段错误,但适用于 malloc

Dynamic 2D Array with realloc gives segmentation fault, but works with malloc

我的动态二维数组有问题。 使用 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] = realloc(gmatrix, cap* sizeof(unsigned));

应该是

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

使用 gmatrix 而不是 gmatrix[i] 将导致 Undefined Behavior and the segmentation fault which you experience is one of the side-effects of Undefined Behavior


编辑:

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

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