
...
Do not delete an array object through a static pointer type that differs from the dynamic pointer type of the object. Deleting an array through a pointer to the incorrect type, results in undefined behavior.
Noncompliant Code Example
In this noncompliant code example, an array of Derived
objects is created and the pointer is stored in a Base *
. Despite Base::~Base
() being declared virtual, this still results in undefined behavior. Further, attempting to perform pointer arithmetic on the static type Base *
, results in a violation of CTR39CTR56-CPP. Do not use pointer arithmetic on polymorphic objects.
Code Block | ||||
---|---|---|---|---|
| ||||
struct Base { virtual ~Base() = default; virtual void f() {} }; struct Derived final : Base {}; void f() { Base *b = new Derived[10]; // ... delete [] b; } |
Compliant Solution
In this compliant solution, the static type of b
is Derived *
, which removes the undefined behavior when indexing into the array as well as when deleting the pointer:
Code Block | ||||
---|---|---|---|---|
| ||||
struct Base { virtual ~Base() = default; virtual void f() {} }; struct Derived final : Base {}; void f() { Derived *b = new Derived[10]; // ... delete [] b; } |
Risk Assessment
Attempting to destruct a polymorphic object which does not have a virtual
destructor declared results in undefined behavior. In practice, potential consequences include abnormal program termination and memory leaks.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP31-CPP | Low | Probable | Low | P6 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
| -analyzer-checker=cplusplus |
Related Vulnerabilities
Search for other vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
CERT C++ Coding Standard | CTR39CTR56-CPP. Do not use pointer arithmetic on polymorphic objects OOP34OOP52-CPP. Do not delete a polymorphic object without a virtual destructor |
Bibliography
[ISO/IEC 14882-2014] | 5.3.5, "Delete" |
...