This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 6.8.2 - A function must not return a reference or a pointer to a local variable with automatic storage duration
Category: Mandatory
Analysis: Decidable,Single Translation Unit
Amplification
This rule also applies to:
- Function parameters passed by value; and
- Returning a lambda that captures by reference a variable with automatic storage duration; and
- Returning a lambda that captures the address of a variable with automatic storage duration.
For the purposes of this rule, a throw that is not caught within the function is considered to be a return from the function.
Rationale
Automatic variables are destroyed when a function returns. Returning a reference or pointer to such a variable allows it to be used after its
destruction, leading to undefined behaviour.
Note: this rule and M23_360: MISRA C++ 2023 Rule 6.8.1.
Example
int32_t * f1()
{
int32_t x = 99;
return &x; // Non-compliant
}
int32_t * f2( int32_t y )
{
return &y; // Non-compliant
}
int32_t & f3()
{
int32_t x = 99;
return x; // Non-compliant
}
int32_t & f4( int32_t y )
{
return y; // Non-compliant
}
int32_t & f5( int32_t & x )
{
return x; // Rule does not apply
}
int32_t * f6()
{
static int32_t x = 0;
return &x; // Rule does not apply
}
void f7()
{
int32_t x = 0;
throw &x; // Non-compliant
}
void f8()
{
try
{
int32_t x = 0;
throw &x; // Rule does not apply - caught within this function
}
catch ( ... )
{
}
}
auto f9()
{
int32_t x { 42 };
return [&x]() {}; // Non-compliant - captures local by reference
}
auto f10()
{
int32_t x { 42 };
return [p = &x]() {}; // Non-compliant - captures address of local
}
The following example is compliant with this rule, but violates M23_360: MISRA C++ 2023 Rule 6.8.1.
int32_t * f11()
{
int32_t i = 42;
int32_t * p = &i;
return p; // Compliant with this rule
}
Copyright The MISRA Consortium Limited © 2023