Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling delete or delete[] on NULL pointer [duplicate]

Is it safe to always omit NULL pointer check before calling delete or delete[], especially while writing cross-platform code sections?

I remember that few years ago (three or four) same code I wrote was working on MS Windows (compiled with MSVCv12 toolchain) but version compiled for Linux with g++ (unfortunately, I do not remember the g++ version) was throwing NULL pointer reference. I found information that it was probably a compiler error at that time.

I've found this SO thread but after reading it I'm still not quite sure if it is safe and if so - from which version of the C++ standard?

like image 267
elklepo Avatar asked May 08 '26 04:05

elklepo


1 Answers

Yes, the standard, since C++98, guarantees that delete or delete[] on a nullpointer has no effect.

C++98 §5.3.5/2

In either alternative, if the value of the operand of delete is the null pointer the operation has no effect.

This was so also before the first standard, when the language was defined by the Annotated Reference Manual.


Regarding

version compiled for Linux with g++ (unfortunately, I do not remember the g++ version) was throwing NULL pointer reference

That's impossible to discuss without a concrete and preferably complete example that reproduces the behavior. It had nothing to do with deleting a nullpointer.

like image 60
Cheers and hth. - Alf Avatar answered May 09 '26 19:05

Cheers and hth. - Alf