On Sun, 21 Aug 2011 18:02:42 -0400 sudhakar govindavajhala wrote: > Hi there, > > Is there a flag in compiling or using gcc/g++ so that a signal like > SIGSEGV in my C++ program will result in an exception being thrown? > If not, why not? I mean, is this is not a reasonable expectation in > OOPS? I suspect you're comparing g++ with the Microsoft Visual Studio C++ compiler. They differ a lot in how they implement exception handling. On Windows, the compiler uses the built-in exception handling feature called SEH, which is language agnostic. On Linux, the entire exception mechanism is provided by libstdc++ with some help from the dynamic linker and it can only handle application level exceptions, not operating system ones (eg. segmentation fault). If you want to handle memory access violations in a try-catch block, you'll have to implement the mechanism yourself. The tricky thing is to return from the signal handler in a part of the main program which actually calls 'throw' to raise an exception. sigaction() can help with that by providing you with the information as to where the exception has occurred. If your application is single threaded, you could use mprotect() from the signal handler to patch the code of a jump to the 'throw' call location and then return from the signal handler. All in all, there are two things you need to keep in mind: * doing too much in the signal handler is bad idea, because there's a good change you'll fault again and end up in a messy situation; * you cannot continue the execution of the program from the signal handler because you'll never be able to return to the code that called the function/method that triggered the fault; If you're working with pointers and are not sure of their contents, you can code a nice little helper like: int access_ok(const void *buf, size_t n); where you open /dev/null and call write() for n bytes. If you get -1 and errno set to EFAULT, you know it's a bad pointer. :-) > Is there anything I need to be careful in throwing an exception in my > signal handlers that convert SIGSEGV to an exception. I will ensure > that no malloc style calls are called. See this link for more details about things you should be careful when working with signals: http://www.kernel.org/doc/man-pages/online/pages/man7/signal.7.html > Thanks for your help. Everything above applies for Unix-like OS-es, though I'm pretty sure MinGW does not use Windows' SEH either. :-) -- Mihai Donțu