Description
Using a pointer or reference to a local variable after its block scope ends accesses an object whose lifetime has ended.
Potential impact
- Reading or writing invalid stack storage can cause incorrect data processing or crashes.
- Other values in the same stack frame may be corrupted.
Remediation
- Do not retain or use a local variable's address beyond its block scope.
- If a longer lifetime is needed, use a caller-owned buffer or a dynamically allocated object with clear ownership.
- In C++, prefer types that express ownership and lifetime safely.
Examples
Before
c
void run(void) {
int *p;
{
int value = 1;
p = &value;
}
*p = 2;
}
After
c
void run(void) {
int value = 1;
int *p = &value;
*p = 2;
}
Explanation:
- Before:
valueis no longer valid after the inner block ends, but it is still accessed throughp. - After: The pointer is used only while the target variable is alive.