Valgrind can be used for a number of things, but currently I’m interested in its memory leak checking ability.
Checking memory leaks with Valgrind
Compile your code (preferably with -g) and then execute it as follows:
valgrind –leak-check=full <program_name> <args>
(For more options, see the man page)
You will get something like this:
==17645== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
==17645== malloc/free: in use at exit: 400 bytes in 1 blocks.
==17645== malloc/free: 1 allocs, 0 frees, 400 bytes allocated.
==17645== For counts of detected errors, rerun with: -v
==17645== searching for pointers to 1 not-freed blocks.
==17645== checked 58,860 bytes.
==17645== 400 bytes in 1 blocks are definitely lost in loss record 1 of 1
==17645== at 0x4021396: malloc (vg_replace_malloc.c:149)
==17645== by 0x80483A5: one (test.c:6)
==17645== by 0x80483CC: main (test.c:12)
==17645== LEAK SUMMARY:
==17645== definitely lost: 400 bytes in 1 blocks.
==17645== possibly lost: 0 bytes in 0 blocks.
==17645== still reachable: 0 bytes in 0 blocks.
==17645== suppressed: 0 bytes in 0 blocks.
==17645== Reachable blocks (those to which a pointer was found) are not shown.
==17645== To see them, rerun with: --show-reachable=yes
If you compiled with -g, you should even see the line number (test.c:6)
I then experimented with multi-threaded programs – valgrind shows the correct memory leak (i.e., my intentional leak multiplied by number of threads). However, I was surprised to see an additional leak message in the output:
==17698== 272 bytes in 2 blocks are possibly lost in loss record 1 of 1
==17698== at 0x40206D5: calloc (vg_replace_malloc.c:279)
==17698== by 0x400FA87: (within /lib/ld-2.4.so)
==17698== by 0x400FB4B: _dl_allocate_tls (in /lib/ld-2.4.so)
==17698== by 0x403AB68: pthread_create@@GLIBC_2.1 (in /lib/tls/i686/cmov/libpthread-2.4.so)
==17698== by 0x80486A7: main (test.c:43)
This leak value is constant, i.e., for 1 thread I get 136 bytes potentially lost. Initially I thought it was a memory leak in the pthread library – but a little googling revealed that it could be memory allocated for thread local storage. Since the function is _dl_allocate_tls, this seems fairly probable. Wish I knew for certain though – anyone care to comment?