No. Feeding a NULL pointer to delete or delete[] is entirely acceptable.
No?
EDIT: if we are not sure if a pointer has been initialized, how can we know that? For example:
1 2 3 4 5 6
type function(int* intPtr)//maybe intPtr is NULL, but if not?
//Well, I have to use it in the function body (dereference it), but I am not sure.
{
//something
}
if we are not sure if a pointer has been initialized, how can we know that?
Well that's a different case. Deleting an uninitialized (or otherwise invalid) pointer will give undefined (but usually not pleasant) results. You can delete a NULL pointer.
If you're calling delete and you expect the pointer to be non-null then you might want to check it just as a self-check for bugs. But you may frequently find yourself with a pointer than might be valid or might be NULL. In that case it's easiest to just call delete and let it do the check for you.
Calling delete on a NULL pointer is fine and will never cause a problem.
Calling delete on an invalid pointer is incorrect and will most likely crash your program.
A pointer being initialized is not the same a pointer being non-NULL.
//Ok, we could have initialized "a" in main,
//but if we don't know what is going on outside the StupidFunction(char*):
void StupidFunction(char* a)
{
if(a)//how can we know if "a" IS NOT INITIALIZED?
//THIS RETURNS FALSE ONLY IF a==NULL OR a==0, can this return true if a is not initialized?
a[0] = 'a';//How can we know if "a" can be dereferenced?
delete[] a;
a = NULL;
}
I think the best you can do is check for null pointers. If the pointer is not initialized with/assigned a proper address or null, that is a problem with the caller's code, not your function.
In the case of StupidFunction the client code must be responsible for feeding the function a pointer it is valid to call delete [] on. There is no way to determine whether that is the case or not inside the function.
More generally, avoid writing code where you're manually calling new/delete/new[]/delete[].
There's no way easy to check whether a non-null pointer is valid. And even if it's valid, how do you know that the data it points to is valid? And how do you know that the call to your function is real and not the result of some buffer overrun that was exploited?
The point is that you have to trust the rest of the program at some point. NULL is an invalid pointer and you can check for that, or just document your API to say that it requires a valid pointer.