AUTOSAR C++14 Rule A20-8-1
An already-owned pointer value shall not be stored in an unrelated smart pointer
Since R2021a
Description
Rule Definition
An already-owned pointer value shall not be stored in an unrelated smart pointer.
Rationale
You use smart pointers to ensure that the memory a pointer points to is automatically deallocated when the pointer is destroyed, for example if the pointer goes out of scope. When unrelated smart pointers manage the same pointer value, one of the smart pointers might attempt to deallocate memory that was already deallocated by the other smart pointer. This results in a double free vulnerability, which corrupts your program's memory management data structure.
A smart pointer owns the pointer value that is used to initialize the smart pointer. If
a pointer value is already owned by a smart pointer such as
std::shared_ptr
, and then you use that smart pointer to initialize
another smart pointer, for example with a copy operation, the two smart pointers are
related. The underlying pointer value is managed by both smart pointers and the memory
pointed to is not deallocated until all the smart pointers are destroyed.
Polyspace Implementation
Polyspace® flags the use of an already-owned pointer as the argument of:
A smart pointer constructor. For instance, in this code snippet,
raw_ptr
is already owned bys_ptr1
and is used to initializes_ptr2
:char *raw_ptr = new char; std::shared_ptr<char> s_ptr1(raw_ptr); std::shared_ptr<char> s_ptr2(raw_ptr); //raw_ptr is already owned by s_ptr1
A smart pointer reset operation. For instance, in this code snippet, the reset of
s_ptr2
replacesraw_ptr2
with already-ownedraw_ptr1
:char *raw_ptr1 = new char; char *raw_ptr2 = new char; std::shared_ptr<char> s_ptr1(raw_ptr1); std::shared_ptr<char> s_ptr2(raw_ptr2); s_ptr2.reset(raw_ptr1); // s_ptr2 releases raw_ptr2 and owns already owned raw_ptr1
Polyspace checks only smart pointer types std::shared_ptr
and
std::unique_ptr
and considers that user-defined allocators and deleters
have standard allocation and deallocation behavior.
A pointer is already owned by a smart pointer if the pointer type is not
std::nullptr_t
and either:
The pointer was used to initialize the smart pointer.
The pointer was used as an argument to the smart pointer
reset()
member function.The pointer is the return value of the smart pointer
get()
member function.The pointer is the return value of the smart pointer
operator->
member function.
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: General utilities library |
Category: Required, Automated |
Version History
Introduced in R2021a