歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux GCC下sizeof內存情況分析

Linux GCC下sizeof內存情況分析

日期:2017/3/1 11:13:17   编辑:Linux編程

情況:

  1. #include <stdio.h>
  2. struct STR
  3. {
  4. double a;
  5. int b;
  6. int c;
  7. char d;
  8. };
  9. struct STR1
  10. {
  11. double a;
  12. char b;
  13. int c;
  14. };
  15. struct STR2
  16. {
  17. char a;
  18. double b;
  19. int c;
  20. };
  21. struct STR3
  22. {
  23. char a;
  24. double b;
  25. int c;
  26. char d;
  27. };
  28. int main()
  29. {
  30. printf("sizeof(struct STR)=%d.\n", sizeof(struct STR));
  31. printf("sizeof(struct STR1)=%d.\n", sizeof(struct STR1));
  32. printf("sizeof(struct STR2)=%d.\n", sizeof(struct STR2));
  33. printf("sizeof(struct STR3)=%d.\n", sizeof(struct STR3));
  34. return 0;
  35. }

輸出結果:

  1. gcc version 4.1.2 20080704 (Red Hat 4.1.2-50)
  2. sizeof(struct STR)=20.
  3. sizeof(struct STR1)=16.
  4. sizeof(struct STR2)=16.
  5. 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字節對齊,即使用了

  1. #pragma pack(8)

也就是說,在GCC下pack命令只有小於等於4才生效。

同樣也就有另一個問題,就是最終大小,在GCC中,要求是最大變量大小的整數倍,但是不超過4字節的倍數,但是VC中,是按照實際大小倍數。

Copyright © Linux教程網 All Rights Reserved