Is there any way to check if pointer is dangling?

Nikhil picture Nikhil · Oct 5, 2011 · Viewed 8.6k times · Source

I have a code where I use a pointer to access some datablock. In some rare cases, a few members of the datablock are empty, and as a result the pointer becomes dangling. In fact, I get the correct pointer but the program crashes when trying to do something with the pointer.

The usual advice would be to avoid this type of usage. But sadly, the framework I use requires that I use this type of data access methods.

Is there a way I can "check" if the pointer is invalid before doing any operation with it? Checking that the pointer is not equal to NULL did not work, obviously. I also tried this:

try
{
    CString csClassName = typeid(*pMyPointer).name();  // Check error condition
    // The line below fails due to dangling pointer (data block is not valid).
    hr = pMyPointer->MyPointerMethod(); 
}
catch(bad_typeid)
{
    return E_FAIL;
}
catch(...)
{
    return E_FAIL;
}

Is it the correct way?

Answer

David Heffernan picture David Heffernan · Oct 5, 2011

There's no way to check whether or not a raw pointer is valid. Invalid pointers are not guaranteed to fail when you access them. Instead of using a raw pointer, you need to use some form of smart pointer.