Skip to content

Instantly share code, notes, and snippets.

@cbarraco
Created October 7, 2016 15:11
Show Gist options
  • Save cbarraco/2ffdb4e5037592ed58d8549fa6c8e70b to your computer and use it in GitHub Desktop.
Save cbarraco/2ffdb4e5037592ed58d8549fa6c8e70b to your computer and use it in GitHub Desktop.
Registers a signal handler that handles exceptions by outputting the program backtrace. Use with the debug flag to include line numbers.
#include <execinfo.h>
#include <stdio.h>
#include <signal.h>
/**
* Outputs the backtrace if the application crashes
* @param signal The signal that was sent when the application crashed
*/
void exception_signal_handler(int signal) {
const int num_backtraces = 20;
void *array[num_backtraces];
int size = backtrace(array, num_backtraces);
printf("Unhandled exception: Signal %d, %s\n", signal, strsignal(signal));
char **err = backtrace_symbols(array, size);
for (int i = 0; i < size; ++i) {
printf("%s\n", err[i]);
}
exit(1);
}
int main() {
signal(SIGSEGV, exception_signal_handler); // Invalid memory reference
*(int*)0=0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment