How to check if a pointer is valid? [duplicate]

Solution 1:

The best bet if you must use raw pointers is to make sure that it is either a valid pointer or NULL. Then you can check if it is valid by checking if it is equal to NULL.

But to answer your question, you can catch these kinds of things with structured exception handling (SEH).

That being said, SEH is a bad idea.

Solution 2:

Catching this kind of errors is addressing the symptoms, not the root cause.

The following idioms will work on any platform:

  • initialize all pointers to zero

  • if you cannot guarantee a pointer is valid, check that it is non-0 before indirecting it

  • when deleting objects, set the pointer to 0 after deletion

  • be careful of object ownership issues when passing pointers to other functions

Solution 3:

There are functions IsBadReadPtr and IsBadWritePtr that might do what you want. There is also an article that explains why you shouldn't use them.

Solution 4:

You can certainly test if the pointer is NULL!

if ( ptr == NULL ) {
   // don't use it
}

That is the only portable test you can do. Windows does provide various APIs to test pointers, but as others have pointed out, using them can be problematic.