Skip to main content

IAR Embedded Workbench for RX 5.20

MEM-stack-global

In this section:
Synopsis

A stack address is stored in a global pointer.

Enabled by default

Yes

Severity/Certainty

High/Medium

highmedium.png
Full description

The address of a variable in stack memory is being stored in a global variable. When the relevant scope or function ends, the memory will become unused, and the externally stored address will point to junk data. This is particularly dangerous because the application might appear to run normally, when it is in fact accessing illegal memory. This might also lead to an application crash, or data changing unpredictably. This check is identical to MISRAC++2008-7-5-2_a, MISRAC++2023-6.8.3_a, MISRAC2004-17.6_b, MISRAC2012-Rule-18.6_b, CERT-DCL30-C_c.

Coding standards
CERT DCL30-C

Declare objects with appropriate storage durations

CWE 466

Return of Pointer Value Outside of Expected Range

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-2

(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++ 2023 6.8.3

(Required) An assignment operator shall not assign the address of an object with automatic storage duration to an object with a greater lifetime

Code examples

The following code example fails the check and will give a warning:

int *px;
void example() {
  int i = 0;
  px = &i; // assigning the address of stack
           // variable a to the global px
}

The following code example passes the check and will not give a warning about this issue:

void example(int *pz) {
  int x; int *px = &x;
  int *py = px; /* local variable */
  pz = px; /* parameter */
}