Padding in union is present or not

一曲冷凌霜 提交于 2019-11-27 21:48:02

问题


Hello all,
I want to know whether union uses padding?
since the size of union is the largest data member size, can there be padding at the end?


回答1:


since the size of union is the largest data member size

That need not be true. Consider

union Pad {
    char arr[sizeof (double) + 1];
    double d;
};

The largest member of that union is arr. But usually, a double will be aligned on a multiple of four or eight bytes (depends on architecture and size of double). On some architectures, that is even necessary since they don't support unaligned reads at all.

So sizeof (union Pad) is usually larger than sizeof (double) + 1 [typically 16 = 2 * sizeof (double) on 64-bit systems, and either 16 or 12 on 32-bit systems (on a 32-bit system with 8-bit char and 64-bit double, the required alignment for double may still be only four bytes)].

That means there must then be padding in the union, and that can only be placed at the end.

Generally, the size of a union will be the smallest multiple of the largest alignment required by any member that is not smaller than the largest member.




回答2:


Union when we use with primitive types inside it

union
{
    char c;
    int x;
}

It seems like it doesn't use padding because the largest size data is anyway is aligned to boundary.

But when we nest a structure within union it does.

    union u
    {
        struct ss
        {
            char s;
            int v;
        }xx;
    }xu;

It resulted in size 8.

so answer for your question is PADDING is persent in UNION.



来源:https://stackoverflow.com/questions/16749343/padding-in-union-is-present-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!