Skip to content

Instantly share code, notes, and snippets.

@reqshark
Created August 11, 2018 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reqshark/323ac0e1e67cd35ae137d8f501e7af7a to your computer and use it in GitHub Desktop.
Save reqshark/323ac0e1e67cd35ae137d8f501e7af7a to your computer and use it in GitHub Desktop.
catch your segfault
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
static void do_segv() {
/* lets do some stuff that would segfault on any system */
int *segv;
segv = 0; /* malloc(a_huge_amount); */
*segv = 1;
/* also try to deref the null pointer wrong, should cause a segfault too */
int* ptr = NULL;
int i = *(int*)0;
}
sigjmp_buf point;
static void handler(int sig, siginfo_t *dont_care, void *dont_care_either) {
longjmp(point, 1);
}
int main(){
struct sigaction sa;
memset(&sa, 0, sizeof(sigaction));
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_NODEFER;
sa.sa_sigaction = handler;
sigaction(SIGSEGV, &sa, NULL); /* ignore whether it works or not */
if (setjmp(point) == 0){
printf("lets do a segfault\n");
do_segv();
} else {
fprintf(stderr, "rather unexpected error\n");
}
return 0; /* program exits clean with no error */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment