Linux GCC下sizeof内存情况分析
Linux GCC下sizeof内存情况分析
情况:
- #include <stdio.h>
- struct STR
- {
- double a;
- int b;
- int c;
- char d;
- };
- struct STR1
- {
- double a;
- char b;
- int c;
- };
- struct STR2
- {
- char a;
- double b;
- int c;
- };
- struct STR3
- {
- char a;
- double b;
- int c;
- char d;
- };
- int main()
- {
- printf("sizeof(struct STR)=%d.\n", sizeof(struct STR));
- printf("sizeof(struct STR1)=%d.\n", sizeof(struct STR1));
- printf("sizeof(struct STR2)=%d.\n", sizeof(struct STR2));
- printf("sizeof(struct STR3)=%d.\n", sizeof(struct STR3));
- return 0;
- }
输出结果:
- gcc version 4.1.2 20080704 (Red Hat 4.1.2-50)
- sizeof(struct STR)=20.
- sizeof(struct STR1)=16.
- sizeof(struct STR2)=16.
- sizeof(struct STR3)=20.
STR: 8+4+4+1=17,同时要求4的倍数,为20。
STR1: 8+1+3+4=16,其中char后面填充了3个字节,因为int必须是4字节对齐,同时16已经为4的倍数。
STR2: 1+3+8+4=16,同上。
STR3: 1+3+8+4+1=17,通STR,结果为20。
一般在VC上结果不同,
VC按照具体的对齐,例如char, double,则一定是16,以double的8对齐,但是GCC中最大以4字节对齐,即使用了
- #pragma pack(8)
也就是说,在GCC下pack命令只有小于等于4才生效。
同样也就有另一个问题,就是最终大小,在GCC中,要求是最大变量大小的整数倍,但是不超过4字节的倍数,但是VC中,是按照实际大小倍数。
评论暂时关闭