Categories
Programming Valgrind

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.

This is a trick I find occasionally invaluable.

10 replies on “Using Valgrind to get stack traces”

Very nice!

Question: For purposes of getting a stack trace, is a special valgrind build needed? Or will a normal build (+ that include and VALGRIND_PRINTF_BACKTRACE call) be enough?

For the same purpose I’ve used NS_ASSERTION combined with XPCOM_DEBUG_BREAK=stack (and fix-linux-stack.pl).

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.

Karellen: backtrace_symbols is essentially useless,
because it shows names only for globally-visible
functions (non-statics).

Comments are closed.