3

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?

stressed_geek
  • 2,118
  • 8
  • 33
  • 45

3 Answers3

5

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.

Paul R
  • 208,748
  • 37
  • 389
  • 560
3

The realloc of weights[2] is trying to realloc unallocated memory, since weights[2] was never assigned any pointer.

Usually, if you want a 2D array, just use wegihts[width*y + x] to index into the array, instead of making an array of pointers.

nawfal
  • 70,104
  • 56
  • 326
  • 368
epsalon
  • 2,294
  • 12
  • 19
2

You can't loop to the new vertice count, as that part of the outer array is not allocated yet and contain uninitialized data. Instead loop to the new num_vertices - 1 and reallocate, then create a brand new weights[num_verticees - 1].

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621