MISRA C++:2023 Rule 6.8.3
An assignment operator shall not assign the address of an object with automatic storage duration to an object with a greater lifetime
Since R2024b
Description
Rule Definition
An assignment operator shall not assign the address of an object with automatic storage duration to an object with a greater lifetime.
Rationale
If you assign the address of an automatic object to another object with a greater
lifetime, then it is possible that the object containing the address remain valid after
the address itself is invalid. For example, consider the pointer
greater_lifetime
. This pointer is assigned the address of the
integer smaller_lifetime
, which is destroyed when the execution exits
the inner code block.
void foo() { int *greater_lifetime; { int smaller_lifetime = 0; greater_lifetime = &smaller_lifetime; } int val = *greater_lifetime; }
greater_lifetime
now points to an
address that is no longer valid, resulting in a dangling pointer. As a result, the
integer val
has an unexpected value.This rule applies when you assign the output of the addressof()
function, &
operator, or the name of an array to an automatic
object. For this rule, if two automatic objects are declared in the same scope, they are
assumed to have same lifetime.
This rule and MISRA C++:2023
Rule 6.8.2
detects trivial and specific instances of potentially
danging pointers and references. Other cases are covered by Rule 6.8.1.
Polyspace Implementation
Polyspace® reports a violation of this rule if you assign the address of an automatic storage object to an object with greater lifetime. Objects with greater lifetime include:
Global pointer variables
Local objects declared at an outer scope
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: Basic concepts |
Category: Mandatory |
Version History
Introduced in R2024b