Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding in union is present or not

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?

like image 249
akash Avatar asked May 25 '13 12:05

akash


People also ask

How do you avoid structure padding in C++?

In Structure, sometimes the size of the structure is more than the size of all structures members because of structure padding. Note: But what actual size of all structure member is 13 Bytes. So here total 3 bytes are wasted. So, to avoid structure padding we can use pragma pack as well as an attribute.

Why does structure padding happen?

The structure padding is automatically done by the compiler to make sure all its members are byte aligned. Here 'char' is only 1 byte but after 3 byte padding, the number starts at 4 byte boundary. For 'int' and 'double', it takes up 4 and 8 bytes respectively.

What is padding in memory?

Structure padding is a concept in C that adds the one or more empty bytes between the memory addresses to align the data in memory.

What is basic difference between padding and packing?

padding makes things bigger. packing makes things smaller. Totally different. @Paolo, that Lost Art link does not show what happens when there is pointer-alignment and the above where two ints might be one after another.


1 Answers

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.

like image 124
Daniel Fischer Avatar answered Oct 26 '22 12:10

Daniel Fischer