delete
From Cppwiki
Operator delete and its counterpart operator delete[], are used to release memory that was allocated through the use of new or new[].
int* foo = new int(0); // ... delete foo;
This example clearly shows the allocation of memory off the heap to create a int. The newed int is then deleted.
delete's effect on the pointer
Operator delete has absolutly no effect on the pointer itself. It will not reassign the pointer to NULL. This is because of C++'s fundamental design goals, and that is in simplicity, and not doing what the programmer does not explicitly ask for.
"delete NULL"
Using NULL as an operand to delete surprisingly (?) isn't undefined behaviour. When delete encounters a NULL operand, it simply does nothing. This makes it useful to assign NULL to pointers you are not using in order to prevent heap corruption.
Incorrect usage of delete
- Main article: allocation symmetry
delete should not be used on something which has already been deleted:
int* foo = new int(0); delete foo; delete foo; // This is referred to as double deletion
delete should not be used on an invalid pointer (that points to data which has not been allocated with new):
int* foo; // Note that the pointer foo is not initialised to NULL. If it were, there would not be a segmentation fault here. delete foo;
The correct form of delete should be used:
int* foo=new int(1); delete foo;
int* bar=new int[2]; delete [] bar;