The following program:
#include <stdlib.h>
int main(void)
{
char *my_str = malloc(42 * sizeof(char));
return 0;
}
Compiled as such:
gcc -g -o prog prog.c
And executed with Valgrind as such:
valgrind --leak-check=full ./prog
Produces the following (truncated) output:
...
==18424== HEAP SUMMARY:
==18424== in use at exit: 42 bytes in 1 blocks
==18424== total heap usage: 1 allocs, 0 frees, 42 bytes allocated
==18424==
==18424== 42 bytes in 1 blocks are definitely lost in loss record 1 of 1
==18424== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18424== by 0x10865B: main (main.c:5)
==18424==
==18424== LEAK SUMMARY:
==18424== definitely lost: 42 bytes in 1 blocks
==18424== indirectly lost: 0 bytes in 0 blocks
==18424== possibly lost: 0 bytes in 0 blocks
==18424== still reachable: 0 bytes in 0 blocks
==18424== suppressed: 0 bytes in 0 blocks
...
Why does Valgrind say that the unfreed memory is "definitely lost"?
From the Valgrind Memcheck docs:
This means that no pointer to the block can be found. The block is classified as "lost", because the programmer could not possibly have freed it at program exit, since no pointer to it exists. This is likely a symptom of having lost the pointer at some earlier point in the program.
However, it's pretty clear that I could have easily freed the block before program exit. What am I missing here? Shouldn't the memory be "still reachable"?