Check For Memory Leaks!

Last week I've lost at least three hours in understanding and fixing a small open source library that was leaking memory. The incredible thing was the amount of allocated memory (half of whom never freed). Basically, the library is a overcomplicated implementation of a binary tree in C that, for less that 1 KB of data, leaks 8 KB of RAM.

My first intention was to throw away that piece of junk code, but unfortunately I didn't have the time to rewrite it, so I started hunting. But understanding the mass of functions and when they are called was taking too long, so I decided to call my old friend Valgrind.

Valgrind is an excellent tool for detecting memory leaks. The simplest way to use it is the following:
valgrind --leak-check=yes program_to_test [parameters]
This is enough to provide you the total amount of allocated memory with a list of blocks that have not been freed (if present). And, for everyone of these, there is the full call hierarchy to let you quickly identify why it was allocated.

Of course, Valgrind can do much more than this but its usage to find memory leaks is the minimum thing that every developer must do before releasing a software. And the fact that the code is open source is not an excuse: you must ensure the quality of your program, no matter how many people will read the source code.

Post a Comment