Main Content

AUTOSAR C++14 Rule M7-5-2

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

Since R2020b

Description

Rule Definition

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.

Rationale

If an object continues to point to another object after the latter object ceases to exist, dereferencing the first object leads to undefined behavior.

Polyspace Implementation

Polyspace® reports a violation of this rule if you assign the address of an automatic storage object to an object with greater lifetime. Objects with greater lifetime include:

  • Global pointer variables

  • Local objects declared at an outer scope

The checker does not raise violations of this rule if a function returns the address of a local variable. AUTOSAR C++14 Rule M7-5-1 covers this situation.

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

char * ptr;
 
void foo (void) {
    char varInFoo;
    ptr = &varInFoo; //Noncompliant
}

void bar (void) {
    char varInBar = *ptr;
}

void main() {
    foo();
    bar();
}

The assignment ptr = &varInFoo is noncompliant because the global pointer ptr might be dereferenced outside the function foo, where the variable varInFoo is no longer in scope. For instance, in this example, ptr is dereferenced in the function bar, which is called after foo completes execution.

In this example, address of local objects in the inner scope is assigned to the pointer pointer_outer_scope, which has a greater lifetime.

#include <cstdint>

void foo()
{
	int8_t *pointer_outer_scope;
	{
		int8_t local_var;
		int8_t local_array[ 10 ];
		int8_t *pointer_inner_scope = nullptr;
		pointer_outer_scope = &local_var;                  // Noncompliant
		pointer_outer_scope = local_array;             // Noncompliant
		pointer_inner_scope = &local_var;                  //Compliant
		pointer_outer_scope = pointer_inner_scope;     // Rule does not apply

	}
}

This rule checks trivial and specific instances of potentially danging pointers and references. For example, the assignment pointer_outer_scope = pointer_inner_scope results in a dangling pointer. Because this assignment does not specifically assign the address of a local object to pointer_outer_scope, this rule does not apply.

Check Information

Group: Declaration
Category: Required, Non-automated

Version History

Introduced in R2020b