C++ Structure: Why returns 'sizeof()' a bigger size than the members actually need?

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

C++ Structure: Why returns 'sizeof()' a bigger size than the members actually need?

Q: Why returns 'sizeof()' a bigger size than the members actually need?

A: This is due to structure alignment which aligns the data structure by padding extra bytes so as to optimize for data transfer.

Modern CPUs perform best in data transfer when fundamental types, such as 'int' and 'float', are stored in memory addresses that are multiples of their length. Some CPUs, like x86, also allow unaligned access but at a performance penalty. In other words, it requires extra data transfer when the data is unaligned.

When a C/C++ compiler processes a structure declaration, it adds extra bytes between fields to ensure that they are properly aligned. It also adds extra bytes to the end of the structure so that every element of an array of that structure type, is properly aligned.

As a rule of thumb, to minimize the extra padded bytes needed for the alignment, all fields of the same type should be grouped together. See the following example:

As the C/C++ standard states, the alignment is completely implementation defined, thus, each CPU/OS/compiler combination is free to choose whatever alignment and padding rules it deems best. Although the standard didn't provide any control in customizing the alignment and padding rules, many compilers provide this through non-standard extensions. For example, VC6 provides the pragma pack(n) macro.