Do NOT always check for NULL! (C++)This tip submitted by Kevin Lam on 2005-01-24 16:44:13. It has been viewed 54551 times.
Rating of 5.7 with 256 votes
First of all, please note that this applies only to C++.
Do NOT check for NULL when allocating memory with new, since new will never return NULL! More information can be found here:
C++ FAQ Lite
As well, if you have:
int *x = new int; ... if(x != NULL) delete x;
That is bad! The language guarantees that if delete is used on a pointer that is NULL, nothing will happen. So instead of testing for NULL (and therefore slowing down your program needlessly), you should just do:
int *x = new int; ... delete x; //Doesn't matter if it's NULL!
[This tip was originally posted in response to a mistake in an earlier tip, which has since been corrected.]
Help your fellow programmers! Add a tip!