Debugging Memory Leaks using Valgrind

Valgrind is a tool for memory debugging, memory leak detection, and profiling. It is named after the main entrance to Valhalla.

Valgrind was originally designed to be a free memory debugging tool for Linux on x86, but has since evolved to become a generic framework for creating dynamic analysis tools such as checkers and profilers.

This post is about using Valgrind to debug memory leaks.

Install Valgrind using:

sudo apt-get install valgrind

Let’s take the following code as example.

#include <stdlib.h>
int main(void)
    int *loc = malloc (10 * sizeof (int));
    loc[10] = 0; //Heap block overrun
    return 0;
} // Memory leak, loc not freed

Compile this code as

gcc example_prog.c

Now let’s run this under valgrind

valgrind --leak-check=yes ./a.out

Now this gives something like this:

==6933== Memcheck, a memory error detector
==6933== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==6933== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==6933== Command: ./a.out
==6933== Invalid write of size 4
==6933== at 0x400512: f (in /home/kt/Desktop/a.out)
==6933== by 0x400522: main (in /home/kt/Desktop/a.out)
==6933== Address 0x51f1068 is 0 bytes after a block of size 40 alloc'd
==6933== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/
==6933== by 0x400505: f (in /home/kt/Desktop/a.out)
==6933== by 0x400522: main (in /home/kt/Desktop/a.out)
==6933== HEAP SUMMARY:
==6933== in use at exit: 40 bytes in 1 blocks
==6933== total heap usage: 1 allocs, 0 frees, 40 bytes allocated
==6933== 40 bytes in 1 blocks are definitely lost in loss record 1 of 1
==6933== at 0x4C2B6CD: malloc (in /usr/lib/valgrind/
==6933== by 0x400505: f (in /home/kt/Desktop/a.out)
==6933== by 0x400522: main (in /home/kt/Desktop/a.out)
==6933== LEAK SUMMARY:
==6933== definitely lost: 40 bytes in 1 blocks
==6933== indirectly lost: 0 bytes in 0 blocks
==6933== possibly lost: 0 bytes in 0 blocks
==6933== still reachable: 0 bytes in 0 blocks
==6933== suppressed: 0 bytes in 0 blocks
==6933== For counts of detected and suppressed errors, rerun with: -v
==6933== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 2 from 2)

The output message states that 40 bytes in 1 block is lost. It also has heap summary and leak summary.

#c, #memory-leaks, #valgrind