Pointer or reference to stack variable leaving scope
Pointer to local variable leaves the variable scope
Description
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 andlocVar
is a local variable.A function performs the assignment
*paramPtr = &locVar
.paramPtr
is a function parameter that is, for instance, anint**
pointer andlocVar
is a localint
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. Polyspace® assumes that the local objects within a function definition are in the
same scope.
Risk
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.
Fix
Do not allow a pointer or reference to a local variable to leave the variable scope.
Examples
Result Information
Group: Static memory |
Language: C | C++ |
Default: On for handwritten code, off for generated code |
Command-Line Syntax: LOCAL_ADDR_ESCAPE |
Impact: High |
Version History
Introduced in R2015bSee Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)