When Should You Check Whether a Pointer Is NULL?
Today I came across a post called “A Couple of Things About Null Pointers”. It covers the same question as the title of this post. Here are a few notes from it.
The problem comes up all the time. We check whether a pointer is NULL in places where the check is unnecessary, then take it for granted in places where we really do need to check.
For example, delete works fine with a null pointer, yet we add a redundant if(ptr!=NULL) check. Passing NULL to strlen, on the other hand, can crash the whole program. We sometimes assume that strlen will check the pointer itself and return when it sees NULL.
A question and answer in the original comments explains why a function such as strlen doesn't do something like if(NULL==ptr)return;. Efficiency is part of the answer, which is very much in the spirit of C. If an argument is invalid, checking it before the call is easier than inspecting the return value afterward. Imagine passing the same argument through several layers of functions and having to check the result of every call. It's simpler to validate it at the point of entry. An implementation can still use an assertion internally to catch a caller's mistake while preserving efficiency in builds where assertions are disabled.
Something to remember the next time you work with pointers.