Every call to new
must be matched by exactly one delete
.
Not zero, and not two. One.
Similarly,
every call to new []
must be matched by exactly one delete []
.
If you don’t call delete
, then the memory is forgotten.
We call this a memory leak.
Sure, the memory will be implicitly freed when the program ends. However, some programs run for a good long time before they end.
What happens if you call delete
more than once?
float *p = new float[100]; delete[] p; delete[] p;
free(): double free detected in tcache 2 SIGABRT: Aborted