Using Valgrind to get stack traces

Sometimes I want to do some printf-style debugging where I print not only some values, but also the stack trace each time a particular code point is hit. GNU provides a backtrace() function that supposedly does this, but I tried it and got hopeless results, little more than code addresses.

Fortunately, you can do this pretty easily with Valgrind. First, add this line somewhere in your source code:

#include <valgrind/valgrind.h>

Then, at the point where you want to print the stack trace, add this:

VALGRIND_PRINTF_BACKTRACE("foo");

You can of course print something other than “foo”. In fact, VALGRIND_PRINTF_BACKTRACE is a variadic printf-style function, so you can do stuff like this:

VALGRIND_PRINTF_BACKTRACE("%s: %d\n", str, i);

You then have to run the program under Valgrind as usual, except you probably should use --tool=none because that’ll run the quickest.

Karellen: I used backtrace_symbols() as well, and it was a debug build with full symbols, and the results were still hopeless. And judging from the man page, even if it worked properly it still won’t give line numbers, which are very helpful.