Pointer to local variable leaves the variable scope
This defect occurs when a pointer or reference to a local variable leaves the scope of the variable. For instance:
A function returns a pointer to a local variable.
A function performs the assignment globPtr
= &locVar. globPtr is a global pointer
variable and locVar is a local variable.
A function performs the assignment *paramPtr
= &locVar. paramPtr is a function
parameter that is, for instance, an int** pointer
and locVar is a local int variable.
A C++ method performs the assignment memPtr
= &locVar. memPtr is a pointer data
member of the class the method belongs to. locVar is
a variable local to the method.
(C++11 and later) A function returns a lambda expression object that captures local variables of the function by reference.
The defect also applies to memory allocated using the alloca function.
The defect does not apply to static, local variables.
Local variables are allocated an address on the stack. Once the scope of a local variable ends, this address is available for reuse. Using this address to access the local variable value outside the variable scope can cause unexpected behavior.
If a pointer to a local variable leaves the scope of the variable, Polyspace® Bug Finder™ highlights the defect. The defect appears even if you do not use the address stored in the pointer. For maintainable code, it is a good practice to not allow the pointer to leave the variable scope. Even if you do not use the address in the pointer now, someone else using your function can use the address, causing undefined behavior.
Do not allow a pointer or reference to a local variable to leave the variable scope.
| Group: Static memory |
| Language: C | C++ |
| Default: On for handwritten code, off for generated code |
Command-Line Syntax: LOCAL_ADDR_ESCAPE |
| Impact: High |
| CWE ID: 562, 825 |