Main Content

MISRA C++:2023 Rule 6.8.3

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

Since R2024b

Description

Rule Definition

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

Rationale

If you assign the address of an automatic object to another object with a greater lifetime, then it is possible that the object containing the address remain valid after the address itself is invalid. For example, consider the pointer greater_lifetime. This pointer is assigned the address of the integer smaller_lifetime, which is destroyed when the execution exits the inner code block.

void foo() {
	int *greater_lifetime;
	{
		int smaller_lifetime = 0;
		greater_lifetime = &smaller_lifetime;
	}
    int val = *greater_lifetime;
}
The pointer greater_lifetime now points to an address that is no longer valid, resulting in a dangling pointer. As a result, the integer val has an unexpected value.

This rule applies when you assign the output of the addressof() function, & operator, or the name of an array to an automatic object. For this rule, if two automatic objects are declared in the same scope, they are assumed to have same lifetime.

This rule and MISRA C++:2023 Rule 6.8.2 detects trivial and specific instances of potentially danging pointers and references. Other cases are covered by Rule 6.8.1.

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

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

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. This assignment is a violation of the rule 6.8.1.

Check Information

Group: Basic concepts
Category: Mandatory

Version History

Introduced in R2024b