简体   繁体   中英

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

I have a problem with my dynamic 2d array. With malloc it worked. With realloc , it failed.

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 .


Edit :

You should initialize gmatrix[i] to NULL after the first malloc as @MattMcNabb pointed out . So use the following after the first call to realloc :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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