Search code examples
cmallocrealloc

How to reallocate memory for a 2D float array?


I tried the following to reallocate a 2D float array whose size chages from 2X2 to 3X3. The code throws a segfault while trying to realloc memory for weights[2].

num_vertices = 2;
float **weights = malloc(num_vertices*sizeof(float *));      // weight array matrix
for(i = 0; i < num_vertices; i++){
    weights[i] = malloc(num_vertices*sizeof(float));
}

num_vertices = 3;
weights = realloc(weights, num_vertices*sizeof(float *));      // weight array matrix
for(i = 0; i < num_vertices; i++){       
    weights[i] = realloc(weights[i], num_vertices*sizeof(float));
}

Of course, I can free the 2D array and malloc again, but I was looking for a more elegant solution. Any ideas?


Solution

  • The problem is that weights[2] contains garbage after you realloc weights.

    You probably want to do something like this:

    new_vertices = 3;
    weights = realloc(weights, new_vertices*sizeof(float *));
    for(i = 0; i < new_vertices; i++)
    {
        if (i >= num_vertices)
            weights[i] = NULL;
        weights[i] = realloc(weights[i], new_vertices*sizeof(float));
    }
    num_vertices = new_vertices;
    

    Note that you have a potential memory leak if realloc ever fails. Since you have no error checking yet though this probably doesn't matter for now.