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:
Then, at the point where you want to print the stack trace, add this:
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.