Return of Stack Variable Address
Description
A function returns the address of a stack variable, which will cause unintended program behavior, typically in the form of a crash.
Examples
Insecure Code
c
int* foo() { int x; return &x; }Secure Code
c
int* foo() { int* x = malloc(sizeof(int)); return x; }Remediation
Instead of returning the address of a stack variable, consider dynamically allocating memory for the variable or re-designing the function to avoid returning addresses of local variables.
Rule Details
| Field | Value |
|---|---|
| ID | CODE-0662 |
| Category | Generic |
| Severity | CRITICAL |
| CWE | CWE-562 |
| Confidence | LOW |
| Impact | HIGH |
| Likelihood | HIGH |
| Exploitability | EASY |
| Tags | memory-safety, stack-variable |
| OWASP | N/A |
References
- https://github.com/struct/mms
- https://www.sei.cmu.edu/downloads/sei-cert-c-coding-standard-2016-v01.pdf
- https://docs.microsoft.com/en-us/cpp/sanitizers/asan-error-examples
- https://rules.sonarsource.com/c/type/Bug/RSPEC-946
- https://cwe.mitre.org/data/definitions/562