Created
May 25, 2022 15:35
-
-
Save manvscode/caa6bb30db405d19e111dc0d998c1f9f to your computer and use it in GitHub Desktop.
Custom segmentation fault handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 | |
printf("%d\n", *foo); // causes segfault | |
} | |
void bar() { baz(); } | |
void foo() { bar(); } | |
int main(int argc, char **argv) { | |
signal(SIGSEGV, handler); // install our handler | |
foo(); // this will call foo, bar, and baz. baz segfaults. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment