AUTOSAR C++14 Rule A18-5-2
Description
Rule Definition
Non-placement new or delete expressions shall not be used.
Rationale
Explicit use of nonplacement new
or delete
operators might result in memory leaks caused by unexpected exceptions or returns. Consider
this code where memory is allocated for a pointer by explicitly calling
new
and deallocated by explicitly calling
delete
.
std::int32_t ThrowError(){ std::int32_t errorCode; std::int31_t* ptr = new std::int32_t{0}; //... if(errorCode!=0){ throw std::runtime_error{"Error"}; } //... if (errorCode != -1) { return 1; } delete ptr; return errorCode; }
If the first
if()
statement istrue
, then the function produces an exception and exits without deleting the pointer.If the second
if()
statement istrue
, then the function returns1
and exits without deleting the pointer.
To avoid an unpredictable memory leak, do not use nonplacement new
and delete
operators. Instead, encapsulate dynamically allocated
resources in objects. Acquire the resources in object constructors and release the resources
in object destructors. This design pattern is called "Resource Acquisition Is
Initialization" or RAII. Following the RAII pattern prevents a memory leak even when there
are unexpected exceptions and returns.
Alternatively, use manager objects that manage the lifetime of dynamically allocated resources. Examples of manager objects in the standard library include:
std::unique_ptr
along withstd::make_unique
std::shared_ptr
along withstd::make_shared
std::string
std::vector
This rule does not apply to a new
operator or a
delete
operator in user-defined RAII classes and managers.
Polyspace Implementation
AUTOSAR C++14 permits explicit resource allocation by calling the new
operator in two cases, when the allocated resource is immediately passed to:
A manager object
A RAII class that does not have a safe alternative to the
new
operator.
Polyspace® flags all explicit uses of the new
operator and the
delete
operator. If you have a process where a new
operator can be permissible and there is no safer alternative, justify the issue by using
comments in your result or code. See:
Address Results in Polyspace User Interface Through Bug Fixes or Justifications if you review results in the Polyspace user interface.
Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access) if you review results in a web browser.
Annotate Code and Hide Known or Acceptable Results if you review results in an IDE.
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: Language support library |
Category: Required, Partially automated |
Version History
Introduced in R2020a