Skip to main content

IAR Embedded Workbench for RX 5.20

MEM-stack-ref (C++ only)

In this section:
Synopsis

A stack object is returned from a function as a reference.

Enabled by default

Yes

Severity/Certainty

High/High

highhigh.png
Full description

A local variable is defined in stack memory, then it is returned from the function as a reference. When the function exits, its stackframe will be considered illegal memory, and thus the return value of the function will refer to an object that no longer exists. Operations on the return value are illegal and an application crash, or memory corruption, is very likely. A safe alternative is for the function to return a copy of the object. This check is identical to MISRAC++2008-7-5-1_a, MISRAC++2023-6.8.2_a.

Coding standards
CERT DCL30-C

Declare objects with appropriate storage durations

CWE 562

Return of Stack Variable Address

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 x;
  return x;
}

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

int example(void) {
  int x;
  return x;
}