How can one grab a stack trace in C? How can one grab a stack trace in C? c c

How can one grab a stack trace in C?


There's backtrace(), and backtrace_symbols():

From the man page:

#include <execinfo.h>#include <stdio.h>...void* callstack[128];int i, frames = backtrace(callstack, 128);char** strs = backtrace_symbols(callstack, frames);for (i = 0; i < frames; ++i) {    printf("%s\n", strs[i]);}free(strs);...

One way to use this in a more convenient/OOP way is to save the result of backtrace_symbols() in an exception class constructor. Thus, whenever you throw that type of exception you have the stack trace. Then, just provide a function for printing it out. For example:

class MyException : public std::exception {    char ** strs;    MyException( const std::string & message ) {         int i, frames = backtrace(callstack, 128);         strs = backtrace_symbols(callstack, frames);    }    void printStackTrace() {        for (i = 0; i < frames; ++i) {            printf("%s\n", strs[i]);        }        free(strs);    }};

...

try {   throw MyException("Oops!");} catch ( MyException e ) {    e.printStackTrace();}

Ta da!

Note: enabling optimization flags may make the resulting stack trace inaccurate. Ideally, one would use this capability with debug flags on and optimization flags off.


For Windows check the StackWalk64() API (also on 32bit Windows). For UNIX you should use the OS' native way to do it, or fallback to glibc's backtrace(), if availabe.

Note however that taking a Stacktrace in native code is rarely a good idea - not because it is not possible, but because you're usally trying to achieve the wrong thing.

Most of the time people try to get a stacktrace in, say, an exceptional circumstance, like when an exception is caught, an assert fails or - worst and most wrong of them all - when you get a fatal "exception" or signal like a segmentation violation.

Considering the last issue, most of the APIs will require you to explicitly allocate memory or may do it internally. Doing so in the fragile state in which your program may be currently in, may acutally make things even worse. For example, the crash report (or coredump) will not reflect the actual cause of the problem, but your failed attempt to handle it).

I assume you're trying to achive that fatal-error-handling thing, as most people seem to try that when it comes to getting a stacktrace. If so, I would rely on the debugger (during development) and letting the process coredump in production (or mini-dump on windows). Together with proper symbol-management, you should have no trouble figuring the causing instruction post-mortem.