内存对齐

#include <stdio.h>

struct TestStruct1{
    char 	a;		//1
    //padding 		//3
    int 	b;		//4
    char 	c; 		//1
    //padding		//3
}TestStruct1;

struct TestStruct2{
    char 	a;		//1
	char 	b; 		//1
	//padding		//2
    int 	c; 		//4
}TestStruct2;

#pragma pack(push, 2)
struct TestStruct3{
    char 	a;		//1
    //padding		//1
	int 	b; 		//4
    char 	c; 		//1
    //padding		//1
}TestStruct3;
#pragma pack(pop)

struct TestStruct4{
    char 	a;		//1
    //padding 		//3
    int 	b;		//4
    char 	c; 		//1
    //padding		//3
}__attribute__((__aligned__(2)))TestStruct4;

struct TestStruct5{
    char 	a;		//1
    //padding 		//3
    int		b; 		//4
	char	c; 		//1
	//padding 		//7
}__attribute__((__aligned__(8)))TestStruct5;

__declspec(align(2)) struct TestStruct6{
    char 	a;		
    int 	b;
    char 	c; 
}TestStruct6;

__declspec(align(8)) struct TestStruct7{
    char 	a;
    int		b;
	char	c;
}TestStruct7;

int main()
{
	printf("TestStruct1:%d\n",sizeof(TestStruct1));		//12
	printf("TestStruct2:%d\n",sizeof(TestStruct2));		//8
	printf("TestStruct3:%d\n",sizeof(TestStruct3));		//8
	printf("TestStruct4:%d\n",sizeof(TestStruct4));		//12
	printf("TestStruct5:%d\n",sizeof(TestStruct5));		//16
	printf("TestStruct6:%d\n",sizeof(TestStruct6));	
	printf("TestStruct7:%d\n",sizeof(TestStruct7));	
}
 

值得说明的几点:

1、不管pragma pack和__attribute__如何指定,结构体内部成员的自对齐仍然按照其自身的对齐值;

2、

__attribute__((__aligned__(8)))
这种方法不能指定内存对齐小于默认对齐,也就是说它只能调大不能调小。而且比较坑的是调小的时候是没任何提示(包括警告和错误),如上第四个例子。

3、SSE指令集的情况下,在VC下才支持__declspec(align(x))这种用法,而对于其他平台不一定有效。也就是g++编译器不一定支持__declspec(align(x))这种写法,我在dev C++下测试__declspec(align(x))这种用法,提示[Warning] 'align' attribute directive ignored [-Wattributes]。


参考博客:

http://blog.youkuaiyun.com/markl22222/article/details/38051483

http://www.cppblog.com/deercoder/archive/2011/03/13/141747.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值