Skip to main content

C++ Is It Safe to Delete a NULL pointer?

Simple answer is YES. It is perfectly safe to delete a null pointer. In C++ delete operator is used to deallocate the memory block pointed by the pointer by releasing the memory allocated via new operator. For basic information on delete operator you can visit this article

Delete operation performs a null pointer check anyway. So performing another null pointer check is an unnecessary operation and for me personally it makes the code ugly. But of course it is a good practice to set the pointer to NULL/nullptr after deleting as the pointer location is invalid after deletion.

However in the industry some people with multiple years of experience in C++ also tend to believe that you need to perform a null pointer check before deleting a pointer. This is because most C++ developers tend to believe if a pointer is not initialized it will get caught from this null pointer check. This is completely wrong.

Below example is to prove my points above.

When the pointer is not initialized the pointer will not be NULL/nullptr. It will contain garbage values. Hence the application will crash. In the below example I have not initialized the pointer, so when I call delete the program will crash.

If you want to learn more in delete vs delete[] please read this article.

  • What happens when delete is used for a null pointer
  • C++ nullptr
  • Delete a pointer in C++