Is it safe to delete a NULL pointer?
And is it a good coding style?
Yes it is safe.
There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.
Since the previous sentence has caused confusion, an example — which isn't exception safe — of what is being described:
void somefunc(void)
{
SomeType *pst = 0;
AnotherType *pat = 0;
…
pst = new SomeType;
…
if (…)
{
pat = new AnotherType[10];
…
}
if (…)
{
…code using pat sometimes…
}
delete[] pat;
delete pst;
}
There are all sorts of nits that can be picked with the sample code, but the concept is (I hope) clear. The pointer variables are initialized to zero so that the delete
operations at the end of the function do not need to test whether they're non-null in the source code; the library code performs that check anyway.