使用 realloc 收缩矩阵

Shrink matrix with realloc

我目前正在尝试了解动态内存分配的工作原理。 我有这个代码:

int main()
{
    int **mat, i;

    mat = calloc(3, sizeof(int*));
    for(i = 0; i < 3; i++)
        mat[i] = calloc(3, sizeof(int));

    mat = realloc(mat, 1*sizeof(int*));
    for(i = 0; i < 1; i++)
        mat[i] = realloc(mat[i], 1*sizeof(int));

    for(i = 0; i < 1; i++)
        free(mat[i]);
    free(mat);

    return 0;
} 

我已经用 valgrind 检查内存泄漏:

 24 bytes in 2 blocks are definitely lost in loss record 1 of 1
 at 0x4C2C975: calloc (vg_replace_malloc.c:711)
 by 0x400605: main (main.c:10)

LEAK SUMMARY:
  definitely lost: 24 bytes in 2 blocks
  indirectly lost: 0 bytes in 0 blocks
    possibly lost: 0 bytes in 0 blocks
  still reachable: 0 bytes in 0 blocks
     suppressed: 0 bytes in 0 blocks

如果我重新分配给 n*sizeof(int),其中 n > 1,则不会发生泄漏。 为什么会这样?

当您减小 mat 数组大小时,您丢失了一些 mat[i] 指针。即 mat[1]mat[2]。在执行 realloc.

之前,您需要手动 free 任何在收缩 realloc 期间丢失的指针