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
- Do not return pointers or references to local variables whose lifetime ends on return.
- Return the value itself or use an output buffer provided by the caller.
- 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:
valuereaches 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.