Main Content

MISRA C:2023 Rule 18.9

An object with temporary lifetime shall not undergo array-to-pointer conversion

Since R2024a

Description

Rule Definition

An object with temporary lifetime shall not undergo array-to-pointer conversion.

Rationale

A temporary object can undergo array-to-pointer conversion if an array is member of a temporary object. For example, the structure my_struct contains an array. It is possible to create a pointer pointing to the member bytes that has a temporary lifetime:

typedef struct my_struct {
	char bytes[10];
} MS;

MS get_my_struct();
p = get_my_struct().bytes;
Calling get_my_struct().bytes creates a temporary structure. The address of the first element of the bytes array of the temporary structure is stored in p. The lifetime of the object pointed to by p ends immediately after this statement. Using this pointer to modify or access the array can result in undefined behavior.

The lifetime of a temporary array ends:

  • When the full expression that generates the temporary array ends, as defined in the C11 Standard.

  • After the next sequence point, as defined in the C90 and C99 Standards. A sequence point is a point in the execution of a program where all previous evaluations are complete and no subsequent evaluation has started yet.

To avoid undefined behavior, store the temporary object containing the array into a named object.

Polyspace Implementation

This rule checker reports a violation If these conditions are met:

  • Your code creates a temporary object, such as a structure or a union, that contains an array.

  • Your code attempts to read or modify the temporary array.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

In this example, the function getStruct() returns an array_wrapper structure. The function foo() creates temporary structures containing arrays by calling getStruct(). Reading or writing into this temporary array is a violation of this rule.

 #include <stdint.h>


typedef struct array_wrapper {
    int a[10];
} AW;

AW getStruct();

void access_array(int *p);

void foo() {
    int* p;
    p = getStruct().a + 1;                 // Noncompliant
    *(&(getStruct().a[1])) = 1;            // Noncompliant
    *(getStruct().a + 1) = 1;              // Noncompliant
    access_array(getStruct().a + 1);       // Noncompliant
}

Check Information

Group: Pointers and Arrays
Category: Required
AGC Category: Required

Version History

Introduced in R2024a