Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ get call stack from std::exception

how can I print the full call stack when a std::exception raises?

like image 342
MBZ Avatar asked Oct 14 '22 02:10

MBZ


1 Answers

If you're using g++ (gcc) and don't mind the code being non-portable, you could try following the wise words of "tombarta":

(shameless copy from tombarta):

#include <execinfo.h>
void print_trace(FILE *out, const char *file, int line)
{
    const size_t max_depth = 100;
    size_t stack_depth;
    void *stack_addrs[max_depth];
    char **stack_strings;

    stack_depth = backtrace(stack_addrs, max_depth);
    stack_strings = backtrace_symbols(stack_addrs, stack_depth);

    fprintf(out, "Call stack from %s:%d:\n", file, line);

    for (size_t i = 1; i < stack_depth; i++) {
        fprintf(out, "    %s\n", stack_strings[i]);
    }
    free(stack_strings); // malloc()ed by backtrace_symbols
    fflush(out);
}

I haven't tried this myself, so I do not know if it works.

like image 166
S.C. Madsen Avatar answered Oct 20 '22 18:10

S.C. Madsen