Welcome 微信登录

首页 / 操作系统 / Linux / Linux GCC下sizeof内存情况分析

情况:
  1. #include <stdio.h>   
  2.   
  3. struct STR  
  4. {  
  5.     double a;  
  6.     int b;  
  7.     int c;  
  8.     char d;  
  9. };  
  10.   
  11. struct STR1  
  12. {  
  13.     double a;  
  14.     char b;  
  15.     int c;  
  16. };  
  17.   
  18. struct STR2  
  19. {  
  20.     char a;  
  21.     double b;  
  22.     int c;  
  23. };  
  24.   
  25. struct STR3  
  26. {  
  27.     char a;  
  28.     double b;  
  29.     int c;  
  30.     char d;  
  31. };  
  32.   
  33. int main()  
  34. {  
  35.     printf("sizeof(struct STR)=%d. "sizeofstruct STR));  
  36.     printf("sizeof(struct STR1)=%d. "sizeofstruct STR1));  
  37.     printf("sizeof(struct STR2)=%d. "sizeofstruct STR2));  
  38.     printf("sizeof(struct STR3)=%d. "sizeofstruct STR3));  
  39.     return 0;  
  40. }  
输出结果:
  1. gcc version 4.1.2 20080704 (Red Hat 4.1.2-50)  
  2. sizeofstruct STR)=20.  
  3. sizeofstruct STR1)=16.  
  4. sizeofstruct STR2)=16.  
  5. sizeofstruct 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字节对齐,即使用了
  1. #pragma pack(8)  
也就是说,在GCC下pack命令只有小于等于4才生效。 同样也就有另一个问题,就是最终大小,在GCC中,要求是最大变量大小的整数倍,但是不超过4字节的倍数,但是VC中,是按照实际大小倍数。