Generate backtrace automatically when program crashes due to SIGSEGV
   For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in execinfo.h to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found in the libc manual.   Here's an example program that installs a SIGSEGV handler and prints a stacktrace to stderr when it segfaults. The baz() function here causes the segfault that triggers the handler:   #include <stdio.h>  #include <execinfo.h>  #include <signal.h>  #include <stdlib.h>  #include <unistd.h>    void handler(int sig) {    void *array[10];    size_t size;     // get void*'s for all entries on the stack    size = backtrace(array, 10);     // print out all the frames to stderr    fprintf(stderr, "Error: signal %d:\n", sig);    backtrace_symbols_fd(array, size, STDERR_FILENO);    exit(1);  }   void baz() {   int *foo = (int*)-1; // make a bad pointer   ...

Comments
Post a Comment