So here’s a cool feature of GNU’s implementation of libc: you can get a stack backtrace (as an array of strings) dynamically in your code. This can be really useful when trying to determine the code path taken when an error occurs. Most times, it’s faster to just run the code in a debugger and use it to display a backtrace, but there are instances when doing it programmatically is your best option. For example, you could get a backtrace in your application’s exception handler and use it to augment error log messages.
First, you need to include execinfo.h to your code:
Next, call the
backtrace() function to get an array of void pointers that represents the current stack (the pointers are the return addresses for each stack frame).
int count = backtrace( tracePtrs, 100 );
backtrace() function returns the number of entries in the array (read the man pages for more info about the array size).
Finally, you need to resolve the function names associated with the pointers. You have 2 options:
backtrace_symbols_fd(). Both of these methods resolve the pointers to strings, but the difference is that
backtrace_symbols() allocates the strings on the heap while
backtrace_symbols_fd() writes the strings to a file descriptor that you can read. Just keep in mind that
backtrace_symbols() won’t work if the heap has been trashed.
Here’s an example using
char** funcNames = backtrace_symbols( tracePtrs, count ); // Print the stack trace for( int ii = 0; ii < count; ii++ ) printf( "%s\n", funcNames[ii] ); // Free the string pointers free( funcNames );
NOTE: Make sure you call
free() on the array of strings returned from
For more information, here’s a good article from the Linux Journal.