Search code examples
cundefined-behaviorstrict-aliasing

Pointer aliasing between struct and first member of struct


Pointer aliasing in C is normally undefined behavior (because of strict aliasing), but C11 standard seems allow aliasing a pointer to struct and a pointer to the first member of the struct

C11 6.7.2.1 (15)...A pointer to a structure object... points to its initial member... and vice versa...

So does the following code contain undefined behavior?

struct Foo {
    int x;
    int y;
};

// does foe return always 100?
int foe() {
    struct Foo foo = { .x = 10, .y = 20 }, *pfoo = &foo;
    int *px = (int*)pfoo; *px = 100;
    return pfoo->x;
}


Solution

  • This code is correct. All versions of Standard C and C++ allow this , although the wording varies.

    There's no strict aliasing issue because you access an object of type int via an lvalue of type int. The strict aliasing rule may apply when the lvalue doing the access has a different type to the object stored at the memory location .

    The text you quoted covers that the pointer cast actually points to the int object.