MEM-stack-pos
Synopsis
Might return address on the stack.
Enabled by default
Yes
Severity/Certainty
High/High

Full description
A local variable is defined in stack memory, then its address is potentially returned from the function. When the function exits, its stackframe will be considered illegal memory, and thus the address returned might be dangerous. This code and subsequent memory accesses might appear to work, but the operations are illegal and an application crash, or memory corruption, is very likely. To correct this problem, consider returning a copy of the object, using a global variable, or dynamically allocating memory. This check is identical to CERT-DCL30-C_b.
Coding standards
- CERT DCL30-C
Declare objects with appropriate storage durations
- CWE 562
Return of Stack Variable Address
Code examples
The following code example fails the check and will give a warning:
int *example(int *a) {
int i;
int *p;
if (a) {
p = a;
} else {
p = &i;
}
return p;
}
The following code example passes the check and will not give a warning about this issue:
int g;
int *example(int *a) {
int i;
int *p;
if (a) {
p = a;
} else {
p = &g;
}
return p;
}