
...
Note that when an operator is called, such as new
, it results in a call to an overloadable operator of the same name, such as operator new()
. These overloadable functions can be called directly but carry the same restrictions as their operator counterparts. That is, calling operator delete()
and passing a pointer parameter has the same constraints as calling the delete
operator on that pointer. Further note that the overloads are subject to scope resolution, so it is possible (but not permissible) to call a class-specific operator to allocate an object, but a global operator to deallocate the object.
...
hidden | true |
---|
...
See MEM33-CPP. Explicitly initiate and terminate object lifetime when performing manual lifetime management for information on lifetime management of objects when using memory management functions other than the new
and delete
operators.
Noncompliant Code Example (placement new()
)
...
Additionally, this code violates MEM08-CPP. Use new and delete rather than raw memory allocation and deallocation.MEM08-CPP. Use new and delete rather than raw memory allocation and deallocation. However, it does not violate MEM33-CPP. Explicitly initiate and terminate object lifetime when performing manual lifetime management because it complies with the MEM33-EX1 exception.
Implementation Details
Some implementations of ::operator new()
result in calling std::malloc()
. On such implementations, the ::operator delete()
function is required to call std::free()
to deallocate the pointer, and the noncompliant code example would behave in a well-defined manner. However, this is an implementation detail and should not be relied on – implementations are under no obligation to use underlying C memory management functions to implement C++ memory management operators.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <cstdlib> struct S { ~S(); }; void f() { S *s = new S(); // ... std::free(s); } |
Additionally, this code violates violates MEM33-CPP. Explicitly initiate and terminate object lifetime when performing manual lifetime management and MEM08-CPP. Use new and delete rather than raw memory allocation and deallocation.
...
Related Guidelines
CERT C++ Coding Standard | MEM33-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 |
...