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中,是按照实际大小倍数。

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值