Tuesday, May 27, 2014

C++: Testing for NULL

Like any good developer I'm constantly learning more about the programming language I work in (C++).  But several of the things I've learned lately have gone against years of working the opposite.

Take for example the following code:

CStudent *pStudent = new CStudent(nStudendId);
if(pStudent)
{
    pStudent->DoSomething();
}


This is a very typical snippet of code.  What's of interest here is the test if pStudent is NULL after the allocation.  If the allocation fails then pStudent would be NULL, and you want to test NULL pointers before dereferencing them which would result in an application crash.  I used to believe that programmers that didn't test the pointer first we being "lazy."  Well, it turns out testing the return value is not only unnecessary, it's actually wasted CPU cycles - so in other words it's bad to test the return from a performance reason.  At the heart of the matter here is the C++ operator 'new.'  If new is unable to allocate the requested block of memory, new throws an exception.  So in the above code, it's impossible for pStudent to ever be NULL.  It will either be a valid block of memory, or an exception will be thrown.

Knowing this is kind of nice.  Code is usually cleaner and easier to read without all these tests against NULL after calling 'new.'  Now let me be clear, this is only when calling 'new.'  Other allocaters such malloc do NOT throw an exception.  So it's still a good idea to test their return.


Related to this, it turns out it's also pointless to test the pointer before freeing the memory.

if(pStudent)
    delete pStudent;

This is a pointless test because 'delete' checks the pointer before proceeding.  So testing the pointer first is again wasted CPU cycles.

Unlike malloc, the same thing is true with 'free.'  The function 'free()' tests the pointer, so there is no need to test before calling free().  But this is not true of all functions that cleanup resources.  The Windows API CloseHandle() does not check, so as the developer it's your job to test before calling CloseHandle().


No comments:

Post a Comment