MISRA C++:2023 Rule 6.8.2
A function must not return a reference or a pointer to a local variable with automatic storage duration
Since R2024b
Description
Rule Definition
A function must not return a reference or a pointer to a local variable with automatic storage duration.
Rationale
Automatic local variables of a function are destroyed when the function returns to its calling function. If the function returns a reference or pointer to such a variable, then the program can attempt to use the variable after its destruction, which leads to undefined behavior. Specifically, this rule applies when a function returns:
A pointer or reference to a parameter that is passed by value
A lambda that captures a local variable by reference
A lambda that captures the address of a local variable
For this rule, a throw
statement that is not caught within
the function is considered a return
from the function.
This rule and MISRA C++:2023 Rule
6.8.3
detect 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 any of these conditions are true:
A function returns a pointer or reference to a local nonstatic variable.
A function returns a lambda that captures a local nonstatic variable by reference or by pointer.
A function throws a pointer or reference to a local variable but does not catch the thrown object within the function body.
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