简体   繁体   中英

C: Realloc twodimensional array created by Malloc

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?

You will completely lose data in your matrix , so this is not really realloc ing 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 free d.

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

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