Last active
March 2, 2023 01:41
-
-
Save mortenpi/3a38c2675a1206e2e0e9dd49bd4b764a to your computer and use it in GitHub Desktop.
Recover gracefully from a segmentation fault (SIGSEGV) in C due to invalid pointer.
This file contains 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
/* | |
Credits to: | |
- https://linux.die.net/man/2/setcontext | |
- https://stackoverflow.com/questions/8456085/why-cant-i-ignore-sigsegv-signal | |
*/ | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdbool.h> | |
#include <signal.h> | |
#include <setjmp.h> | |
bool debug_catch_sigsegv_mode = false; | |
static jmp_buf jbuf; | |
void debug_signal_handler(int signo) | |
{ | |
if(debug_catch_sigsegv_mode) { | |
//printf("\nsignal_handler: received %d\n", signo); | |
siglongjmp(jbuf, 1); | |
} else { | |
SIG_DFL(signo); | |
} | |
} | |
void debug_enable_sigsev_handler() { | |
if(signal(SIGSEGV, debug_signal_handler) == SIG_ERR) { | |
printf("enable_sigsev_handler: ERROR, can't catch SIGSEGV\n"); | |
} | |
} | |
void debug_print_pointer(const void* ptr) | |
{ | |
long ptr_deref; | |
printf("debug_print_pointer(%p) = ", ptr); | |
debug_catch_sigsegv_mode = true; | |
if(ptr != NULL && sigsetjmp(jbuf, !0) == 0) { | |
ptr_deref = *(long*)ptr; | |
printf("[%016lx]", ptr_deref); | |
} else { | |
printf("<segmentation fault>"); | |
} | |
debug_catch_sigsegv_mode = false; | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment