AUTOSAR C++14 Rule M7-5-1
A function shall not return a reference or a pointer to an automatic variable (including parameters), defined within the function
Description
Rule Definition
A function shall not return a reference or a pointer to an automatic variable (including parameters), defined within the function.
Rationale
Local objects of a function are destroyed at the end of a function call. If you return the address of such an object via a pointer, you might access a destroyed object. For instance:
int* foo(int a){
int b = a^2;
return &b;
}foo() returns a pointer to b. The variable
b goes out of scope at the end of the function call and the pointer
returned by foo() points to a destroyed object. Accessing the pointer
leads to undefined behavior.Polyspace Implementation
Polyspace® raises a violation if a function returns a reference or pointer to a variable that goes out of scope at the end of the function call.
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: Declaration |
| Category: Required, Non-automated |