Check For Memory Leaks!

Last week, I've lost at least three hours in understanding and fixing an overcomplicated implementation of a binary tree in the shape of an open source C library.

The problem was the amount of allocated space, half of whom never freed: for less than 1 KB of user data, it leaked 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. Understanding the logic behind that mass of functions 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 unfreed blocks (if present). For every block, there is the full call hierarchy to let you quickly identify why it was allocated.

Valgrind can do much more than this, but using it to find memory leaks is the minimum thing that every developer must do before considering its job done. Releasing your software under an open source license is not an excuse. You must ensure the quality of your code, no matter how many people can potentially fix it.


Cover image by Rupert Lees currently used as Valgrind logo.

This post has been updated after its initial publication. Last change made on 2017/01/01.