Short answer: nothing happens
In C++, delete on a null pointer does nothing. The language defines this case as having no effect, so the call is safe. You do not need an if check first.
A small example
#include <iostream>
int main() {
int* p = nullptr;
delete p; // Does nothing.
delete[] p; // Also does nothing.
std::cout << "Still running\n";
return 0;
}
The program prints Still running. Both delete and delete[] accept a null pointer without error.
Why an if check is not needed
Some code wraps delete in a check:
if (p != nullptr) {
delete p;
}
The check is redundant. It does no harm, but the delete on its own is enough.
Deleting twice is a different problem
Deleting a null pointer is safe. Deleting a pointer that has already been deleted is not, because that pointer still holds the old, non-null address. Doing it again is undefined behavior.
A common habit is to reset the pointer after deleting it:
int* p = new int(42);
delete p;
p = nullptr; // Later deletes through p do nothing.
delete p;
Resetting p protects only this variable. Other copies of the same address still hold the old value, so they need their own handling.
Class types and destructors
For class types, delete on a null pointer does not call a destructor, because there is no object to destroy.
Memory leaks are a different problem
Deleting a null pointer is safe, but forgetting to delete memory you allocated causes a leak. Readers often ask, what tools can I use to detect memory leaks? Valgrind is a common choice on Linux.
Smart pointers such as std::unique_ptr free their memory automatically when they go out of scope, so you call delete directly much less often.
Summary
deleteon a null pointer has no effect and is safe.delete[]on a null pointer is also safe.- Deleting the same non-null pointer twice is undefined behavior.
- Setting a pointer to
nullptrafter deleting it prevents repeated deletes through that variable only.