Main Content

Overlapping assignment

Memory overlap between left and right sides of an assignment

Description

This defect occurs when there is a memory overlap between the left and right sides of an assignment. For instance, a variable is assigned to itself or one member of a union is assigned to another.

Risk

If the left and right sides of an assignment have memory overlap, the behavior is either redundant or undefined. For instance:

  • Self-assignment such as x=(int)(long)x; is redundant unless x is volatile-qualified.

  • Assignment of one union member to another causes undefined behavior.

    For instance, in the following code:

    • The result of the assignment u1.a = u1.b is undefined because u1.b is not initialized.

    • The result of the assignment u2.b = u2.a depends on the alignment and endianness of the implementation. It is not defined by C standards.

    union {
       char a;
       int b;
    }u1={'a'}, u2={'a'}; //'u1.a' and 'u2.a' are initialized
    
    u1.a = u1.b; 
    u2.b = u2.a;

Fix

Avoid assignment between two variables that have overlapping memory.

Examples

expand all

#include <string.h>

union Data {
    int i;
    float f;
};

int main( ) {
    union Data data;
    data.i = 0;
    data.f = data.i;

    return 0;
}

In this example, the variables data.i and data.f are part of the same union and are stored in the same location. Therefore, part of their memory storage overlaps.

Result Information

Group: Programming
Language: C | C++
Default: Off
Command-Line Syntax: OVERLAPPING_ASSIGN
Impact: Low

Version History

Introduced in R2015b