简体   繁体   English

具有realloc的动态2D阵列会产生分段错误,但可与malloc一起使用

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

I have a problem with my dynamic 2d array. 我的2D动态数组有问题。 With malloc it worked. 使用malloc可以正常工作。 With realloc , it failed. 使用realloc ,它失败了。

This dosen't work: 这行不通:

#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;
        }
    }

}

But this does: 但这确实是:

#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;
        }
    }

}

In the first code part I get a segmentation fault error. 在第一个代码部分中,我遇到了分段错误错误。 Why? 为什么?

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

should be 应该

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

Using gmatrix instead of gmatrix[i] will lead to Undefined Behavior and the segmentation fault which you experience is one of the side-effects of Undefined Behavior . 使用gmatrix代替gmatrix[i]将导致未定义行为 ,而您遇到的分段错误是未定义行为的副作用之一。


Edit : 编辑

You should initialize gmatrix[i] to NULL after the first malloc as @MattMcNabb pointed out . @MattMcNabb 指出,在第一个malloc之后,应将gmatrix[i]初始化为NULL So use the following after the first call to realloc : 因此,在第一次调用realloc之后使用以下命令:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM