Data Structure Alignment 2
In a previous article, it seemed that the basic rules of structure alignment were understood, but some areas were ambiguous. For example, see this program below.
According to the previous rules it is easy to figure out that sizeof (A) =16, sizeof (B) =24. But the result of running under GCC is not so, so for a moment a bit do not know the problem, memory alignment is the work of the compiler, so the implementation of the following platform is not uniform specification, although you can # pragma pack set itself, but there are problems.
Summarize:
1. After aligning the padding to each member, the alignment of the structure depends on the size of the largest member inside it, for example, if the maximum member of the struct is of type int, it will eventually be aligned by 4B. It is
particularly important to note that if the largest member is of type double, it will behave inconsistently on different platforms, 8B aligned under Windows VC, and 4B aligned under Linux gcc (You can set its 8B alignment with the GCC option-malign-double.)
2. #pragma pack cannot increase the default packing and can only be reduced. So this also brings up some subtle problems.
CODE:
#include <stdio.h>struct a{int a;short b;int C;char D;}; struct b1{double a;short b;int C;char D;}; #pragma pack (push,8) struct b2{double a;short b;int C;char D;}; #pragma pack (POP) #pragma pack (push,4) struct b3{double a;short b;int C;char D;}; #pragma pack (POP) #pragma pack (push,1) struct b4{double a;short b;int C;char D;}; #pragma pack (pop) struct c{int a;short B[2];char c[2];}; int main () {printf ("A:%d\n", sizeof (struct a));p rintf ("B1:%d\n", sizeof (struct B1));p rintf ("B2:%d\n", sizeof (struct B2 );p rintf ("B3:%d\n", sizeof (struct B3));p rintf ("B4:%d\n", sizeof (struct B4));p rintf ("C:%d\n", sizeof (struct C)); return 0;}
Operation Result:
For the size of the A,C structure, it is readily available according to the two rules.
The key is that the struct b,double is aligned to 4B by default under GCC.
Reference:
(1) Wikipedia
For 32-bit x86:
- A Char (one byte) would be 1-byte aligned.
- A Short (bytes) would be 2-byte aligned.
- a int (four bytes) would be 4-byte aligned.
- A Long (four bytes) would be 4-byte aligned.
- A float (four bytes) would be 4-byte aligned.
- A Double (eight bytes) would be 8-byte aligned on Windows and 4-byte aligned on Linux (8-byte with -malign-dou ble compile time option).
- A Long Long (eight bytes) would be 8-byte aligned.
- A long double (ten bytes with C++builder and DMC, eight bytes with Visual C + +, twelve bytes with GCC) would be 8-b Yte aligned with C++builder, 2-byte aligned with DMC, 8-byte aligned with Visual C + + and 4-byte aligned with GCC.
- Any pointer (bytes) would be 4-byte aligned. (e.g.: char*, int*)
(2) http://blog.csdn.net/vonzhoufz/article/details/32131801
Data Structure Alignment 2