Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching segfaults in C

I have a program that segfaults from pointer arithmetic sometimes. I know this happens, but I can't easily check ahead of time to see whether it segfaults or not - either I can "pre-scan" input data to see if it will cause a segfault (which can be impossible to determine), or I can refit it to not use pointer arithmetic, which would require a significantly larger amount of work, or I can try to catch a segfault. So my question:

1) How, in C, can I catch a segfault? I know something in the OS causes a segfault, but what can a C program do in the event that it segfaults to die a bit more gracefully than just Segmentation fault?

2) How portable is this?

I imagine this is a highly unportable behavior, so if you post any code to catch a segfault, please tell me what it works on. I'm on Mac OS X but I'd like my program to work on as many platforms as it can and I want to see what my options are.

And don't worry - basically all I want to do is print a more user-friendly error message and free some malloc()ed memory, and then die. I'm not planning on just ignoring all segfaults I get and plowing ahead.

like image 862
Chris Lutz Avatar asked Feb 16 '09 18:02

Chris Lutz


1 Answers

Well, SIGSEGV is trappable, and this is POSIX, so it is portable in that sense.

Bu I'm concerned that you seem to want to handle the segfault rather than fix the problem that causes the segfault. If I had to pick whether it was the OS at fault, or my own code, I know which I would choose. I suggest you hunt down that bug, fix it, then write a test case to make sure it never bites you again.

like image 156
Paul Beckingham Avatar answered Sep 30 '22 07:09

Paul Beckingham