CERT.MEM.SMART_PTR.OWNED

The pointer value '{0}' is already owned

A defect will be reported where ownership of the same pointer object is acquired by two different smart pointer objects.

Vulnerability and risk

Attempting to delete a memory twice is undefined behaviour and can lead to corruption of the program memory management data, thereby allowing a malicious user to read or write values from otherwise protected addresses.

Vulnerable code example

Copy
#include <memory>
void foo () {
 int * p = new int;
 std::unique_ptr<int> ptr1(p);
 std::unique_ptr<int> ptr2(p);
}

Klocwork reports defect CERT.MEM.SMART_PTR.OWNED on line 5 stating "The pointer value 'p' is already owned". The pointer 'p' was passed to the constructor of the smart pointer 'ptr1' on line 4, and so it's lifetime is now managed by 'ptr1'. Passing 'p' to the constructor of 'ptr2' on line 5 results in two separate smart pointer objects managing a single resource.

Fixed code example

Copy
#include <memory>
 
void foo () {
 
int * p = new int;
std::unique_ptr<int> ptr1(p);
ptr1.release ();
std::unique_ptr<int> ptr2(p);
}

The call to 'ptr1.release()' on line 7 results in 'ptr1' no longer managing the resource pointed to by 'p'.

External guidance

Extension

The MSPO.ACQ attribute can be added to APIs that acquire ownership of smart pointers and will act as sources and sinks. The MSPO.REL attribute can be added to APIs that result in the smart pointer no longer controlling the lifetime of the pointed to object.