If I have a pointer pMem which i allocate dynamically with new, should i check for null before delete, like this:
if (pMem)
delete pMem;
Is checking for null necessary?
Three answers:
?
2011-05-07 00:07:36 UTC
No need to check for null. The delete command ignores the call if the pointer is null, so you can safely call: delete pMem; The if statement is redundant and useless. If the pointer contains already deleted address or uninitialized garbage value, the if statement will still not be able to save you from disaster. So in the end, the "if (pMem) " doesn't protect you against anything!
It is mentioned in 2nd Edition C++ FAQ book - that it is a bad programming practice in C++ to write such code. Also note that if you are thinking about the resulting performance hit due to function called by delete, there is none, because the builtin implementation of delete is always inline. So there is no function call at all.
Hope that helps!
Cubbi
2011-05-07 20:17:32 UTC
> The coding guidelines in my company mentions one should always check for null.
If this is in regards to "delete pMem;", then look for a new job.
If this is in regards to writing functions that dereference pointers (execute any expression containing *pMem), then it is exactly right. Dereferencing a null pointer is an error, but calling delete on it is not (although it certainly is a design flaw: the way the program itself is written should make this an impossiblity)
Kevan
2011-05-07 06:39:30 UTC
For most good programmers, it's a good option to consider checking for a null value.
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.