Main Content

AUTOSAR C++14 Rule M7-5-1

A function shall not return a reference or a pointer to an automatic variable (including parameters), defined within the function

Description

Rule Definition

A function shall not return a reference or a pointer to an automatic variable (including parameters), defined within the function.

Rationale

Local objects of a function are destroyed at the end of a function call. If you return the address of such an object via a pointer, you might access a destroyed object. For instance:

int* foo(int a){
	int b = a^2;
	return &b;
}
The function foo() returns a pointer to b. The variable b goes out of scope at the end of the function call and the pointer returned by foo() points to a destroyed object. Accessing the pointer leads to undefined behavior.

Polyspace Implementation

Polyspace® raises a violation if a function returns a reference or pointer to a variable that goes out of scope at the end of the function call.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

int gVal;
//...

int* foo(void){
	int val;
	//...
	return &val;//Noncompliant 
}

In this example, the function foo() returns the address of val. This local variables goes out of scope at the end of the function call. Accessing the pointer returned by foo() results in undefined behavior. Polyspace raises a violation.

Check Information

Group: Declaration
Category: Required, Non-automated

Version History

Introduced in R2019a

expand all