If you allocate memory, and deliberately choose not to hold a pointer to it, then you cannot free it.
C++ gives you enough rope to hang yourself with, and allows you to aim a gun at your own foot.
That is nothing new.
The other mistake is checking the value of p
to see if it was allocated successfully.
Only on older compilers does new
return NULL
if it fails. On newer compilers, a failed new
will result in throwing a std::bad_alloc
exception.
So in this code, (assuming you are using a compiler from the last decade) you know that either:
- the
new
succeeded, and p
is valid/non-NULL.
- or an exception was thrown.
There is no way for p
to end up NULL
!
Even if p
could end up NULL, calling delete
on a NULL
value is perfectly safe, and there is nothing wrong with it.
So your example code could well be:
int main()
{
int *p = new int; // Will throw exception if fails
new int; // Deliberate Mem Leak
delete p; // No need to check NULL
system("PAUSE"); // Pause to see results (NOTE: this is skipped if an exception is thrown!)
return 0;
}