Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/Catch a segmentation fault on Linux

I have a Linux C++ application and I'd like to test an object pointer for validity before dereferencing it. However try/catch doesn't work for this on Linux because of the segmentation fault. How can this be done?

like image 651
jackhab Avatar asked Feb 05 '09 09:02

jackhab


3 Answers

If you have a scenario where many pointers across your app reference the same limited-lifetime objects, a popular solution is to use boost smart pointers. Edit: in C++11, both of these types are available in the standard library

You would want to use shared_ptr for pointer(s) that are responsible for the lifetime of your object and weak_ptr for the other pointers, which may become invalid. You'll see that weak_ptr has the validity check you're asking for built in.

like image 55
Drew Dormann Avatar answered Oct 16 '22 07:10

Drew Dormann


A segmentation fault is not an Exception (like Java's NullPointerException); it is a signal sent from the OS to the process. Have a look at the manpage for sigaction for pointers on how to install a handler for the segmentation fault (SIGSEGV).

like image 34
Joao da Silva Avatar answered Oct 16 '22 06:10

Joao da Silva


You could enable a signal handler for SIGSEGV for this one occurrence. See the man page "signal" for details. The other alternative is to use references which are guaranteed to be valid. It depends on your application of course.

like image 5
Greg Reynolds Avatar answered Oct 16 '22 06:10

Greg Reynolds