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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With