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 Responses to Using Valgrind to get stack traces

  1. Sweet, thanks!

  2. 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?

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

  4. Anthony Catel

    Thanks for the tip. Valgrind FTW !

  5. It also works on MacOS, which doesn’t have backtrace(),
    afaik.

  6. GNU provides a backtrace() function that supposedly does this, but I tried it and got hopeless results, little more than code addresses.

    Yes, that’s why there is also backtrace_symbols(3) to get function names, if available. See:

    http://www.kernel.org/doc/man-pages/online/pages/man3/backtrace.3.html

    • Nicholas Nethercote

      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.

  7. Great!

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