Returning a stack address

Returning an address into stack storage

Description

Returning a pointer or reference to a local variable whose lifetime ends when the function returns leaves the caller using invalid stack memory.

Potential impact

  • Dereferencing the returned pointer may cause a crash or undefined behavior.
  • Stack reuse may expose sensitive or incorrect data.

Remediation

  1. Do not return pointers or references to local variables whose lifetime ends on return.
  2. Return the value itself or use an output buffer provided by the caller.
  3. If dynamic allocation is necessary, define ownership transfer and document who must release the memory.

Examples

Before

c
int *make_value(void) {
    int value = 42;
    return &value;
}

After

c
int make_value(void) {
    int value = 42;
    return value;
}

Explanation:

  • Before: value reaches the end of its lifetime when the function returns, so its returned address is invalid.
  • After: Returning a copy of the value avoids exposing a stack address.

References