Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an illegal aliasing? [duplicate]

Aside from that the ints in the following example might not be layouted as if they werre following in a normal array: is this an illegal aliasing in C++ ?

struct S
{
    int a, b;
};

void fn( S &s )
{
    (&s.b)[-1] = 123;
}

1 Answers

It is illegal (undefined behavior, see @user17732522's comment and this question pointed out by @Özgür Murat Sağdıçoğlu for why exactly).

Even for POD (plain old data) types, compilers are allowed to include padding between members. In the case of

struct S
{
    int a, b;
};

there is very likely no padding, as both members have the same alignment requirements (I could however find no reference, if that is required by the standard).

In another case like

struct S
{
    char a;
    int b;
};

there will be an implementation defined amount of padding between the members and pointer magic, like you did in your question will be non-portable at least.

Generally speaking the standard gives you the following guarantees about the memory layout of POD types [1]:

  • You can safely convert a pointer to the first member to the whole struct and vica versa.
  • You can use the offsetof macro [2] to get the offsets of the different members.

Thus when working with pointers to data members, try to use those facilities and avoid relying on false assumptions about the data layout.

like image 105
Jakob Stark Avatar answered Sep 19 '25 00:09

Jakob Stark