December 19th, 2003, 12:29 AM
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.
// Results from VC6 on x86, it may varies for other CPU/OS/compiler combination.
int sizeA = sizeof(MyStructA); // sizeA = 1 + 1 + (2-padding) + 4 = 8
int sizeB = sizeof(MyStructB); // sizeB = 1 + (3-padding) + 4 + 1 + (3-padding) = 12
Last edited by Andreas Masur; July 24th, 2005 at 05:06 AM.
Click Here to Expand Forum to Full Width
This is a Codeguru.com survey!