I am currently trying to understand how dynamic memory allocation works. I have this code:
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;
}
I have checked with valgrind for memory leaks:
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
The leaks don't occur if I reallocate to n*sizeof(int) where n > 1. Why is this happening?
When you reduce the mat
array size you have lost some of the mat[i]
pointers. Namely mat[1]
and mat[2]
. You need to manually free
any pointers that will be lost during the shrink realloc
before doing the realloc
.