CERT.EXPR.TEMP_OBJ.MOD

Do not modify objects with temporary lifetime.

The CERT.EXPR.TEMP_OBJ.MOD checker detects modifications to objects with temporary lifetime in C99 and later. When a function returns a struct or union containing an array, and the return value is not stored in a named variable, modifying the array element through subscript causes undefined behavior.

This checker is applicable only to the modern engine.

Vulnerability and risk

Temporary objects can expose members or array elements that appear writable even though the containing object does not have a stable lifetime. Writing through those expressions can result in undefined behavior and unreliable program results.

Mitigation and prevention

Assign the returned value to a named object before modifying its members or elements. Avoid storing pointers to, or writing through, array-to-pointer conversions and member access expressions based on temporary objects.

Vulnerable code example

Copy
struct S1 {
    int array[10];
};

struct S1 getS1(void);

void update_element(int value)
{
    getS1().array[3] = value;
}

In this noncompliant example, the code writes to an array element of a temporary structure value. Because the structure returned by getS1() has temporary lifetime, the write can result in undefined behavior.

Fixed code example

Copy
struct S1 {
    int array[10];
};

struct S1 getS1(void);

void update_element(int value)
{
    struct S1 result = getS1();
    result.array[3] = value;
}

The compliant solution stores the returned value in a named object before modifying its array element.

External guidance