Stack Trace in Linux

This is incase I forget how to print out my current stack in linux:

#include <execinfo.h>

size_t sz;
void *bt[20];
char **strings;

sz = backtrace(bt, 20);
strings = backtrace_symbols(bt, sz);

for(int i = 0; i < sz; ++i)
fprintf(stderr, “%s\n”, strings[i]);

2 Responses to “Stack Trace in Linux”

  1. Scott says:

    That’s cool!

    Why not run it through gdb?

  2. ejohnson says:

    For several reasons. I had a similar error occuring twice during startup of my application and I was trying to find out the call stack in both cases. I wanted to see the callstack in both locations and wouldn’t have been able to do that at once had I forced a crash and looked through a core file.

    Likewise, stepping through code with GDB isn’t always the most convenient thing to do when multiple source files are involved. So, why not just print out the stack myself?

    Also, what if an non-critical error condition occurs and I want to have a stack trace but contnue execution? I can log this, recover from the error, and continue execution. Then I can go back later and figure out what went wrong.

Leave a Reply