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?
Initialize your pointer to NULL. If after some processing it is still NULL it’s invalid, otherwise it’s valid.
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.
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).
How do you test the pointer for validity? Compare to NULL?
The best thing you do is to run your program under Valgrind. A bug might be in a quite different place.
Update: On Win32 platform there is something like __try __except which allows to catch some exceptions. As far I know there is no Linux equivalent for that Win32 feature.
If you attach a handler to the SIGSEGV there isn't much you can do besides log the fact that the error occurred and fail gracefully. Your program is in an undefined state when this violation occurs and it therefore may not be safe to continue normal operation.
Beyond checking for NULL I don't believe there is a way to check if a pointer is 'valid' in the sense you are describing. During normal operation errors like this shouldn't happen as they represent a bug, so you should want your program to fail, albeit gracefully.
Pointers are stored in objects. They are initialized in the constructor, potentially to 0 (NULL). They're deleted in the destructor, possibly in assignment and rarely in other functions. When deleted in members other than the destructor, they're immediately assigned a new value or 0.
There is no natural, universal way with raw C++ pointers. C++ assumes that you will track that information.
In most situations, you can handle this by remembering to set pointers to NULL when they are invalid. New pointers that initially don't point should be set to NULL and newly deleted objects should have their pointers set to NULL.
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.
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.
Generally, regarding the pretty weird idea of "checking a non-NULL pointer for validity", have a look at this article: http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx ("IsBadXxxPtr should really be called CrashProgramRandomly")