Valgrind, The Ultimate Memory Debugger

Valgrind is an open-source memory debugger for GNU/Linux on x86/x86-64 (and other environments) written by Julian Seward, already known for having committed Bzip2. It is the best news for programmers for years. Valgrind is so powerful, so beautifully designed that you definitely should wander on the Valgrind Home Page.

In the case of the Tiger Compiler Project correct memory management is a primary goal. To this end, Valgrind is a precious tool, as is dmalloc, but because STL implementations are often keeping some memory for efficiency, you might see “leaks” from your C++ library. See its documentation on how to reclaim this memory. For instance, reading the GCC’s C++ Library FAQ, especially the item “memory leaks” in containers is enlightening.

I (Akim) personally use the following shell script to track memory leaks:

#! /bin/sh

exec 3>&1
exec valgrind --num-callers=20		\
              --leak-check=yes		\
              --leak-resolution=high	\
              --show-reachable=yes	\
              "$@" 2>&1 1>&3 3>&-	|
  sed 's/^==[0-9]*==/==/' >&2 1>&2 3>&-

The output is too long to be displayed here but you should try it yourself, for instance on 0.tig.

Starting with GCC 3.4, GLIBCPP_FORCE_NEW is spelled GLIBCXX_FORCE_NEW.

As in the case of GDB, you should be careful when running a libtoolized program in Valgrind. Use the following command to make sure that this is your tc binary (and not the shell) that is checked by Valgrind:

$ libtool exe valgrind tc

You can ask Valgrind to run a debugger when it catches an error, using the --db-attach option. This is useful to inspect a process interactively.

$ valgrind --db-attach=yes ./tc

The default debugger used by Valgrind is GDB. Use the --db-command option to change this.

Another technique to make Valgrind and GDB interact is to use Valgrind’s gdbserver and the vgdb command (see Valgrind’s documentation for detailed explanations).