【发布时间】:2017-04-12 18:50:11
【问题描述】:
我目前正在尝试了解动态内存分配的工作原理。 我有这个代码:
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 > 1 的 n*sizeof(int),则不会发生泄漏。 为什么会这样?
【问题讨论】:
-
当您减小
mat数组大小时,您丢失了一些mat[i]指针。即mat[1]和mat[2]。