This is undefined behavior . The pointer must come from new or must be a null pointer.
Standard (N3797) 5.3.5 [expr.delete] / 2
If the operand is of type class, the operand is converted to a type pointer by calling the above conversion function, and the converted operand is used instead of the original operand for the rest of this section. In the first variant (delete an object), the value of the delete operand can be the value of a null pointer, a pointer to an object without an array created by the previous new expression, or a pointer to a subobject (1.8) representing the base class of such an object (item 10). If not, the behavior is undefined.
[...]
The part left below is the same for delete [] .
Deletion is only valid for
- null pointers
- pointers you received from the new
- or a base class pointer pointing to the above.
Zero pointers:
To track null pointers, calling delete on a null pointer is noop, and the pointer is still a null pointer (no need to reassign nullptr ). This is guaranteed, at least for the standard delete and release functions. If you define custom, you must also handle this correctly.
Standard 5.3.5 [expr.delete] / 7
If the value of the operand of the delete-expression is not the value of a null pointer, then:
Otherwise, it will not be indicated whether the release function will be called. [Note. The release function is called regardless of whether the destructor for the object or any element of the array throws an exception. - final note]
So, delete can do nothing at all, or it can call the null pointer deallocation function. Let's look at this function as follows:
Standard 3.7.4.2 [basic.stc.dynamic.deallocation] / 3
If the release function completes by throwing an exception, the behavior is undefined. The value of the first argument passed to the release function may be the value of a null pointer; if so, and if the release function is included in the standard library, the call does not work.
[...]
It is explicitly mentioned that it is not valid.
Note. . If you define your own memory deallocation functions, you must make sure that you process them the same way. Incorrect handling of null pointers would be evil.