Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Do not create an unrelated smart pointer object with a pointer value is that owned is owned by another smart pointer object. This includes resetting a smart pointer's managed pointer to an already-owned pointer value, such as by calling reset().

...

In this noncompliant code example, the poly pointer value owned by a std::shared_ptr object is cast to the D * pointer type with dynamic_cast() in an attempt to obtain a std::shared_ptr of the polymorphic derived type. However, this eventually results in undefined behavior as the same pointer is thereby stored in two different std::shared_ptr objects. When g() exits, the pointer stored in derived is freed by the default deleter. Any further use of poly results in accessing freed memory. When f() exits, the same pointer stored in poly is destroyed, resulting in a double-free vulnerability.

...

In this compliant solution, the dynamic_cast() is replaced with a call to std::dynamic_pointer_cast(), which returns a std::shared_ptr of the polymorphic type with the valid shared pointer value. When g() exits, the reference count to the underlying pointer is decremented by the destruction of derived, but because of the reference held by poly (within f()), the stored pointer value is still valid after g() returns.

...

Passing a pointer value to a deallocation function that was not previously obtained by the matching allocation function results in undefined behavior, which can lead to exploitable vulnerabilities.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM56-CPP

High

Likely

Medium

P18

L1

Automated Detection

Tool

Version

Checker

Description

 

 

 

Astrée

Include Page
Astrée_V
Astrée_V

dangling_pointer_use

Axivion Bauhaus Suite

Include Page
Axivion Bauhaus Suite_V
Axivion Bauhaus Suite_V

CertC++-MEM56
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

DF4721, DF4722, DF4723


Parasoft C/C++test

Include Page
Parasoft_V
Parasoft_V

CERT_CPP-MEM56-a

Do not store an already-owned pointer value in an unrelated smart pointer

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C++: MEM56-CPPChecks for use of already-owned pointers (rule fully covered)

PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V1006

 


Related Vulnerabilities

Search for other vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Bibliography

[ISO/IEC 14882-2014]Subclause 20.8, "Smart Pointers"

...


...

 Image Modified Image Modified