Tip 6: valgrind

From Vlsiwiki
Jump to: navigation, search

Valgrind is a memory problem detector. It can detect memory leaks, access to uninitialized memory, run-away pointers, etc. It does this by intercepting all malloc and new calls in C and C++. It only runs on x86-based systems.

In order to run it, you must compile with debugging information using the "-g" flag:

gcc -o test -g test.c

with this program:

#include <stdio.h>
int main()
{
 char *p;
 // Allocation #1 of 19 bytes
 p = (char *) malloc(19);
 // Allocation #2 of 12 bytes
 p = (char *) malloc(12);
 free(p);
 // Allocation #3 of 16 bytes
 p = (char *) malloc(16);
 return 0;
}

Then, run valgrind on your resulting binary with a SMALL test case:

valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes ./test

As it runs, this will output a report that looks like this:

==1846== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 5 from 1)
==1846== malloc/free: in use at exit: 35 bytes in 2 blocks.
==1846== malloc/free: 3 allocs, 1 frees, 47 bytes allocated.
==1846== For counts of detected errors, rerun with: -v
==1846== searching for pointers to 2 not-freed blocks.
==1846== checked 68,712 bytes.
==1846== 
==1846== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==1846==    at 0x4A05809: malloc (vg_replace_malloc.c:149)
==1846==    by 0x400513: main (test.c:12)
==1846== 
==1846== 
==1846== 19 bytes in 1 blocks are definitely lost in loss record 2 of 2
==1846==    at 0x4A05809: malloc (vg_replace_malloc.c:149)
==1846==    by 0x4004E9: main (test.c:7)
==1846== 
==1846== LEAK SUMMARY:
==1846==    definitely lost: 35 bytes in 2 blocks.
==1846==      possibly lost: 0 bytes in 0 blocks.
==1846==    still reachable: 0 bytes in 0 blocks.
==1846==         suppressed: 0 bytes in 0 blocks.

The first malloc corresponds tot he 19 bytes that are definitely lost. This is because the pointer is immediately reassigned to the 12 byte malloc. The 12 bytes, however, are properly freed. After this, another 16 bytes are allocated and then not freed at the end of the program. Remember, C technically does not do garbage collection!