0

I have a two-dimensional int array allocated as follows:

int **matrix = (int**)malloc(x * sizeof(int));
for (i = 0; i < x; i++)
    matrix[i] = (int*)malloc(y * sizeof(int));

If I do realloc this array by the following code

int **matrix = (int**)realloc(matrix, x * sizeof(int));
for (i = 0; i < x; i++)
    matrix[i] = (int*)malloc((y) * sizeof(int));

will there be any leftover "tails" of second dimension of the array and should I use free() function for them before reallocating, or they will go away themselves?

chqrlie
  • 131,814
  • 10
  • 121
  • 189
1valdis
  • 1,009
  • 1
  • 15
  • 27

2 Answers2

1

You will completely lose data in your matrix, so this is not really reallocing anything; you could just as well free and malloc the top-level array, getting possibly better performance. Furthermore your code would leak memory, because the 2nd level allocations are not freed.

1

Here is how you can resize the 2D matrix while keeping the current values intact, initializing the newly allocated cells to 0 and freeing any extra leftovers:

// matrix was allocated to x and y
// reallocate it to newx, newy
for (i = newx; i < x; i++) { /* free unneeded rows */
    free(matrix[i]);
}
matrix = realloc(matrix, sizeof(*matrix) * newx);
for (i = x; i < newx; i++) { /* initialize the new row pointers */
    matrix[i] = NULL;
}
for (i = 0; i < newx; i++) {
    matrix[i] = realloc(matrix[i], sizeof(*matrix[i]) * newy);
    for (int j = y; j < newy; j++)
        matrix[i][j] = 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189