
...
The C++ programming language adds additional ways to allocate memory, such as the operators new
, new[]
, and placement new
, and allocator objects. Unlike C, there are multiple ways with which to free dynamically allocated memory, such as the operators delete
, delete[]()
, and deallocation functions on allocator objects.
Do not call a deallocation function on anything other than nullptr
, or a pointer returned by the corresponding allocation function described by:
Allocator | Deallocator |
---|---|
operator new()/new | operator delete ()/delete |
operator new[]()/new[] | operator delete[]()/delete[] |
placement operator new () | N/A |
allocator<T>::allocate() |
|
std::malloc() , std::calloc() ,std::realloc() | std::free() |
...
In the first alternative (delete object), the value of the operand of
delete
may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined. In the second alternative (delete array), the value of the operand ofdelete
may be a null pointer value or a pointer value that resulted from a previous array new-expression. If not, the behavior is undefined.
Deallocating a pointer that is not allocated dynamically (including pointers obtained by calls to placement new()
) is undefined behavior because the pointer value was not obtained by an allocation function. Deallocating a pointer that has already been passed to a deallocation function is undefined behavior because the pointer value no longer points to memory that has been dynamically allocated.
...
CERT C++ Coding Standard | MEM53-CPP. Explicitly initiate and terminate object lifetime when performing manual lifetime management |
CERT C Secure Coding Standard | MEM31-C. Free dynamically allocated memory when no longer needed |
MITRE CWE | CWE 590, Free of Memory Not on the Heap CWE 415, Double Free CWE 404, Improper Resource Shutdown or Release CWE 762, Mismatched Memory Management Routines |
...