compile
# g++ -rdynamic ./test_stacktrace.cpp -o test_stacktrace
./test_stacktrace.cpp: In function ‘int main(int, char**)’:
./test_stacktrace.cpp:63:25: error: invalid use of non-static member function
signal(SIGSEGV, b.trace);
code
/*
* g++ -rdynamic ./test_stacktrace.cpp -o test_stacktrace
*/
#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
class Backtrace {
public:
Backtrace();
void trace(int sig);
};
Backtrace::Backtrace(){}
void Backtrace::trace(int sig){
void *trace[10];
char **messages = (char **)NULL;
int i, trace_size = 0;
trace_size = backtrace(trace, 10);
messages = backtrace_symbols(trace, trace_size);
fprintf(stderr, "Error: signal %d:\n", sig);
for(i=1; i<trace_size; ++i){
fprintf(stderr, "#%d %s\n", i, messages[i]);
}
exit(1);
}
void baz(){
int *foo = (int*)-1;
printf("%d\n", *foo);
}
void bar() { baz(); }
void foo() { bar(); }
int main(int argc, char **argv){
Backtrace b;
signal(SIGSEGV, b.trace);
foo();
}