-
-
Save khanh101/5bc94e16523d9e708b930aeec40a4741 to your computer and use it in GitHub Desktop.
Catching SIGSEGV (Segmentation Faults) in C
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
// This code installs a custom signal handler for the SIGSEGV signal | |
// (segmentation fault) and then purposefully creates a segmentation | |
// fault. The custom handler `handler` is then entered, which now | |
// increases the instruction pointer by 1, skipping the current byte | |
// of the faulty instruction. This is done for as long as the faulty | |
// instruction is still active; in the below case, that's 2 bytes. | |
// Note: This is for 64 bit systems. If you prefer 32 bit, change | |
// `REG_RIP` to `REG_EIP`. I didn't bother putting an appropriate | |
// `#ifdef` here. | |
#include<string.h> | |
#include<signal.h> | |
#include<stdio.h> | |
void handler(int nSignum, siginfo_t* si, void* vcontext) { | |
printf("segmentation fault\n"); | |
ucontext_t* context = (ucontext_t*)vcontext; | |
context->uc_mcontext.gregs[REG_RIP]++; | |
} | |
int main() { | |
printf("start\n"); | |
struct sigaction action; | |
memset(&action, 0, sizeof(struct sigaction)); | |
action.sa_flags = SA_SIGINFO; | |
action.sa_sigaction = handler; | |
sigaction(SIGSEGV, &action, NULL); | |
int* x = 0; | |
int y = *x; | |
printf("end\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment