Stack use after scope

Stack storage used after its scope ends

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

  1. Do not retain or use a local variable's address beyond its block scope.
  2. If a longer lifetime is needed, use a caller-owned buffer or a dynamically allocated object with clear ownership.
  3. 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: value is no longer valid after the inner block ends, but it is still accessed through p.
  • After: The pointer is used only while the target variable is alive.

References