Recovering from a segfault in C
by admin on Oct.21, 2023, under News
To return to a safe point in our program after a segmentation fault or other signal, we can make use of the setjmp() and longjmp() functions provided in the setjmp.h header. These functions allow us to jump back to a point in our program where setjmp() was called, bypassing the normal function call/return flow.
Here’s an example that demonstrates how to use setjmp() and longjmp() to recover from a segmentation fault:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <setjmp.h>
static jmp_buf jump_buffer;
void segfault_handler(int signo) {
printf("Caught segfault! Recovering...\n");
longjmp(jump_buffer, 1); // Jump back to where setjmp was called
}
int unsafe_function() {
int *ptr = NULL;
*ptr = 42; // This will cause a segmentation fault
return *ptr;
}
int main() {
// Set up the segfault handler
if (signal(SIGSEGV, segfault_handler) == SIG_ERR) {
fprintf(stderr, "Can't set up segfault handler\n");
exit(1);
}
printf("Setting up recovery point...\n");
if (setjmp(jump_buffer) == 0) {
printf("Running unsafe function...\n");
int result = unsafe_function();
printf("Result: %d\n", result);
} else {
printf("Recovered from segfault. Resuming normal operation.\n");
}
printf("Continuing program...\n");
// ... Rest of your program logic
return 0;
}




