MISRA C++:2008 Rule 7-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.1
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: Declarations |
| Category: Required |
Version History
Introduced in R2013b1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.