First, while the fill specification is supplemented by the compiler, the OS also imposes some rules regarding alignment requirements. This answer assumes you are using gcc, although the OS may vary
To determine the space occupied by a given structure and its elements, you can follow these rules:
First, suppose that a structure always starts with an address that is correctly aligned for all data types.
Then for each entry in the structure:
- The minimum space required is the raw size of the element specified by
sizeof(element) . - The element alignment requirement is the alignment requirement for the base element type. Remarkably, this means that the alignment requirement for the
char[20] array is the same as the requirement for a simple char .
Finally, the alignment requirement of the structure as a whole is the maximum value of alignment requirements for each of its elements.
gcc will insert padding after the given element to ensure that the next (or structure, if we are talking about the last element) are correctly aligned. He will never reorder the elements in the structure, even if it will save memory.
Now the alignment requirements themselves are also a bit odd.
- 32-bit Linux requires 2-byte data types to have 2-byte alignment (their addresses must be even). All larger data types must have 4-byte alignment (addresses end with
0x0 , 0x4 , 0x8 or 0xC ). Note that this also applies to types that are larger than 4 bytes (for example, double and long double ). - The 32-bit version of Windows is more stringent, if the type of K-bytes is in size, it must be byte-aligned. This means that a
double can only be placed at an address ending in 0x0 or 0x8 . The one exception to this is a long double , which is still 4-byte aligned, even if it is actually 12 bytes. - For Linux and Windows on 64-bit machines, the K byte type must be byte-aligned. Again,
long double is an exception and must be aligned by 16 bytes.
Abhay Buch Mar 25 '11 at 18:41 2011-03-25 18:41
source share