Search code examples
cmultidimensional-arraysegmentation-faultmallocrealloc

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?


Solution

  • 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));
    }