Hi guys!
I'm new to programming in C++ on Linux so i run into a strange problem. I was trying to catch segmentation fault but i couldnt. Though i placed try..catch block around the code that tries to write some value to the begining of RAM my program successfully crashed and i only saw "SegmentationFault" as its output. So my question is how to catch segmentation faults in C++ on Linux. Any help appreciated.

Note however that it's not guaranteed that you can continue from a SIGSEGV - but you should be able to catch the fault.

--
Mats

03-19-2008

brewbuck

Quote:

Originally Posted by matsp

Note however that it's not guaranteed that you can continue from a SIGSEGV - but you should be able to catch the fault.

Just don't try to be clever by throwing a C++ exception from inside the SIGSEGV handler. It would be awesome if that worked, but it doesn't.

According to POSIX, the behavior of a program is undefined after it received an asynchronous SIGSEGV. In practice, many system will attempt to retry the faulting instruction after the handler finishes. If you return from the signal handler, chances are it's just going to be called again, in an infinite loop. The only thing you can really do is print an error (carefully!) and call exit().

03-19-2008

matsp

Quote:

Originally Posted by brewbuck

According to POSIX, the behavior of a program is undefined after it received an asynchronous SIGSEGV. In practice, many system will attempt to retry the faulting instruction after the handler finishes. If you return from the signal handler, chances are it's just going to be called again, in an infinite loop. The only thing you can really do is print an error (carefully!) and call exit().

Or, you could use setjmp()/longjmp() to continue executing somewhere completely different.

--
Mats

03-19-2008

brewbuck

Quote:

Originally Posted by matsp

Or, you could use setjmp()/longjmp() to continue executing somewhere completely different.

Thereby jumping past all kinds of destructors and leaking resources right and left? ;)

But that's a problem for C programs as well. At least in C you can build an "unwind list" which you can process prior to a longjmp(). In C++ it's nearly impossible because there is no way to deliberately trigger a destructor. Well, you can call ~Class() directly, but that doesn't release memory since it has no idea whether the object is heap or stack... It's a gnarly problem.

In practice, just set a global flag from your signal handler, and periodically check it in the main body of code. If you see that it's set, THEN you can throw an exception and everything will unwind properly. But that doesn't work for SIGSEGV for reasons already mentioned...