This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 21.6.2 - Dynamic memory shall be managed automatically
[expr.delete]
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
A program shall not take the address of or use:
- Any non-placement form of
new or delete;
- Any of the functions
malloc, calloc, realloc, aligned_alloc, free;
- Any member function named
allocate or deallocate enclosed by namespace std;
-
std::unique_ptr::release.
Rationale
The use of dynamic memory requires the tracking of any memory resources that are allocated to ensure that they are released appropriately (no
memory leaks, no double frees, use of a matching deallocation function). This is likely to be error prone (possibly leading to undefined
behaviour) if it is not managed automatically using facilities such as std::make_unique or std::vector.
In addition, C-style allocation is not type safe and does not invoke constructors or destructors.
Note: the use of placement new, which is non-allocating, is restricted by M23_329: MISRA C++ 2023 Rule 21.6.3.
Example
class A { /* ... */ };
auto p1 = static_cast< A * >( malloc( sizeof( A ) ) ); // Non-compliant
auto p2 = new A; // Non-compliant
auto p3 = std::make_unique< A >(); // Compliant
auto p4 = p3.release(); // Non-compliant
void f1( std::pmr::memory_resource & mr, A * p )
{
void * iptr = mr.allocate( sizeof( A ) ); // Non-compliant
delete p; // Non-compliant - undefined behaviour if p was allocated using new[]
}
Copyright The MISRA Consortium Limited © 2023