Data Structure Alignment 2
在前面的一篇文章中,似乎明白了结构体对齐的基本规则,但是有些地方还是含糊不清。比如看下面的这个程序。
根据前面的规则很容易算出,sizeof(A)=16, sizeof(B)=24.但是在GCC下运行的结果却不是这样,所以一时有点不知问题所起,内存对齐都是编译器做的工作所以各个平台下面的实现没有得到统一规范,虽然可以#pragma pack自己设定,但是也存在问题。
总结:
1.对各个成员对齐padding之后,结构的对齐要看里面最大成员的size,比如如果struct里面最大成员是int类型,则最终按4B对齐。特别注意的是如果最大成员是double类型的话就会在不同平台上表现不一致,在Windows VC下面是8B对齐,在Linux GCC下面是4B对齐(可以通过gcc选项-malign-double设置其8B对齐)。
2.#pragma pack不能增大默认的packing,只能减小。所以这同样会带来一些微妙的问题。
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));
printf("B1: %d\n", sizeof(struct B1));
printf("B2: %d\n", sizeof(struct B2));
printf("B3: %d\n", sizeof(struct B3));
printf("B4: %d\n", sizeof(struct B4));
printf("C: %d\n", sizeof(struct C));
return 0;
}
运行结果:

对于A,C结构的大小,根据那两条规则很容易得到。
关键是struct B,double在GCC下面默认要按照4B对齐。
参考:
(1)Wikipedia
For 32-bit x86:
- A char (one byte) will be 1-byte aligned.
- A short (two bytes) will be 2-byte aligned.
- An int (four bytes) will be 4-byte aligned.
- A long (four bytes) will be 4-byte aligned.
- A float (four bytes) will be 4-byte aligned.
- A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux (8-byte with -malign-double compile
time option).
- A long long (eight bytes) will be 8-byte aligned.
- A long double (ten bytes with C++Builder and DMC, eight bytes with Visual C++, twelve bytes with GCC) will be 8-byte aligned with C++Builder, 2-byte aligned
with DMC, 8-byte aligned with Visual C++ and 4-byte aligned with GCC.
- Any pointer (four bytes) will be 4-byte aligned. (e.g.: char*, int*)
(2) http://blog.csdn.net/vonzhoufz/article/details/32131801
Data Structure Alignment 2
原文:http://blog.csdn.net/vonzhoufz/article/details/44940599