Verifying Pointers in C++

December 22, 2009

no comments

It is well known that C++ is having a few problems with pointers…

When we used C style malloc( ) and free( ) we verified the returned pointer. If the pointer was NULL (zero) then it was invalid and should not be used.

Going to C++ we have constructors. A constructor does not have a return value so the only way to notify the caller that the construction failed was using an exception. If my object is using an internal buffer and the system is out of memory then my constructor has to throw an out-of-memory exception.

The caller who created my object using the new operator will have to catch the exception. This is the only way to know that the creation of the object had failed. Constructors cannot return NULL because an object can also be created in the local scope and then there is no return value.

All this means that the following is a logical error:

MyClass *ptr = new MyClass(12);

if (!ptr) return(ERROR_CODE_FAIL);

There is an error because C++ will make sure that an exception is thrown in case of an error so the code flow will break before the second line and therefore the second line will only execute if the pointer has a valid value.

Here is one way to do this correctly:

MyClass *ptr = null;try { ptr = new MyClass(12); } catch(…) { ptr = NULL; }if (!ptr) return(ERROR_CODE_FAIL);

You can also look for the reserved word nothrow which is a Microsoft Visual C++ extension.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>