Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are 'partially overlapping objects'?

I was just going through all the possible Undefined Behaviours in this thread, and one of them is

The result of assigning to partially overlapping objects

I wondered if anyone could give me a definition of what "partially overlapping objects" are and an example in code of how that could possibly be created?

like image 280
Tony The Lion Avatar asked Sep 03 '11 11:09

Tony The Lion


1 Answers

As pointed out in other answers, a union is the most obvious way to arrange this.

This is an even clearer example of how partially overlapping objects might arise with the built in assignment operator. This example would not otherwise exhibit UB if it were not for the partially overlapping object restrictions.

union Y {
    int n;
    short s;
};

void test() {
    Y y;
    y.s = 3;     // s is the active member of the union
    y.n = y.s;   // Although it is valid to read .s and then write to .x
                 // changing the active member of the union, .n and .s are
                 // not of the same type and partially overlap
}

You can get potential partial overlap even with objects of the same type. Consider this example in the case where short is strictly larger than char on an implementation that adds no padding to X.

struct X {
    char c;
    short n;
};

union Y {
    X x;
    short s;
};

void test() {
    Y y;
    y.s = 3;     // s is the active member of the union
    y.x.n = y.s; // Although it is valid to read .s and then write to .x
                 // changing the active member of the union, it may be
                 // that .s and .x.n partially overlap, hence UB.
}
like image 51
CB Bailey Avatar answered Nov 15 '22 12:11

CB Bailey