MEM-stack
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 stack frame 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 MISRAC++2008-7-5-1_b, MISRAC2004-17.6_a, MISRAC2012-Rule-18.6_a, CERT-DCL30-C_a, MISRAC++2023-6.8.2_b.
Coding standards
- CERT DCL30-C
Declare objects with appropriate storage durations
- CWE 562
Return of Stack Variable Address
- MISRA C:2004 17.6
(Required) The address of an object with automatic storage shall not be assigned to another object that may persist after the first object has ceased to exist.
- MISRA C:2012 Rule-18.6
(Required) The address of an object with automatic storage shall not be copied to another object that persists after the first object has ceased to exist
- MISRA C++ 2008 7-5-1
(Required) A function shall not return a reference or a pointer to an automatic variable (including parameters), defined within the function.
- MISRA C++ 2023 6.8.2
(Mandatory) A function must not return a reference or a pointer to a local variable with automatic storage duration
Code examples
The following code example fails the check and will give a warning:
int *example(void) {
int a[20];
return a; //a is a local array
}
The following code example passes the check and will not give a warning about this issue:
#include <stdlib.h>
int* example(void) {
int *p,i;
p = (int *)malloc(sizeof(int));
return p; //OK - p is dynamically allocated
}