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?
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With