一.为什么要内存对齐
经过内存对齐之后,CPU的内存访问速度大大提升;
内存空间按照byte划分,从理论上讲似乎对任何类型的变量的访问可以从任何地址开始,但实际情况是在访问特定变量的时候经常在特定的内存地址访问,这就需要各类型数据按照一定的规则在空间上排列,而不是顺序的一个接一个的排放,这就是对齐。
二. 内存对齐原则
1、数据成员对齐规则:结构(struct或联合union)的数据成员,第一个数据成员放在offset为0的地方,以后每个数据成员存储的起始位置: min(#pragma pack()指定的数,这个数据成员的自身长度)的倍数
2、结构体作为成员:如果一个结构里有某些结构体成员,则结构体成员要从min(#pragram pack() , 内部长度最长的数据成员)的整数倍地址开始存储。(struct a里存有struct b,b里有char,int,double等元素,那b应该从min(#pragram pack(), 8)的整数倍开始存储。)
3、结构体的总大小,也就是sizeof的结果,必须是 min(#pragram pack() , 长度最长的数据成员) 的整数倍
#pragram pack() 默认为4(32位), 8(64位)
三. 用例
// #pragma pack(4)
struct s1{
double b;
char a;
} s1;
struct s2{
char a;
double b;
} s2; typedef struct s3{
char a;
int b;
double c;
} s3;
typedef struct s4{
char a;
double c;
int b;
} s4; struct s5{
char a;
s3 s;
int b;
} s5;
struct s6{
char a;
s4 s;
int b;
} s6;
加上 #pragma pack(4):
s1-s6 : 12, 12, 16, 16, 24, 24
不加 #pragma pack(4):(64位默认8):
s1-s6 : 16, 16, 16, 24, 32, 40 特别注意的是: c结构体中不允许定义static变量; C++结构体中可以定义static变量,sizeof时不计算该变量, 但需注意初始化格式,
C++ sizeof几种变量的计算方法: https://blog.****.net/lime1991/article/details/44536343
四. 更改编译器缺省字节对齐方式方法 法1. #pragma pack()用法
#pragma pack(n) /*指定按n字节对齐,等价于#pragma pack(push,n), n必须为2的n次方,否则编译器可能会报错*/
#pragma pack() /*取消指定对齐,恢复缺省对齐,等价于#pragma pack(pop)*/
链接:https://baike.baidu.com/item/%23pragma%20pack/3338249 参数介绍 法2.__attribute__((packed))用法
__attribute__((aligned(n))) // 让所作用的数据成员对齐在n字节的自然边界上;如果结构中有成员的长度大于n,则按照最大成员的长度来对齐;
__attribute__((packed)) // 取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐
注意: 两个括号不能少 用例:
typedef struct s2{
char a;
int b;
double c;
} __attribute__((aligned(4))) s2;
typedef struct __attribute__((packed)) s2{
char a;
double c;
int b;
} s2;
五. 位域类型用法
注意,结构体内可以定义:位域类型; 位域类型没怎么接触过,有时间的话专门写一篇进行下详细了解;
参考链接: https://www.cnblogs.com/tsw123/p/5837273.html
struct A1{
char f1 : ;
char f2 : ;
char f3 : ;
}A1;
struct A2{
char f1 : ;
char f2 ;
char f3 : ;
}A2;
struct A3{
char f1 : ;
short f2 ;
char f3 : ;
}A3;
struct A4{
char f1 : ;
int f2 : ;
char f3 : ;
}A4;
sizeof结果
A1-A4: 2, 3, 6, 4
六 常见的几种误用
#pragma pack(4) typedef struct s00{
char b;
int a;
} s00; char c_temp[] = "";
s00 s_temp = { 0x09, 0x12345678};
此时, sizeof(s_temp) = 8, 内存中((char*)&s_temp)[0-7] = 0x09, 0x00,0x00,0x00,0x78,0x56,0x34,0x12 ;
1. memset(&s_temp, 0, sizeof(s_temp));
此时,memset会将8个字节都设为0, 在这里由于struct s_temp一般为malloc申请空间, malloc(sizeof(s00)), 默认申请为8个字节, 所以memset不会出错;
若直接定义结构体s00 s_temp, 需考虑a后三个字节值可能不定,默认为0;
2. (s00*)c_temp;
若是将一个char*的数组强转为s00, 该数组没有考虑b后的三个空字符,那么强转后参数就会出错,
假设 c_temp[0-7] = 0x78,0x56,0x34,0x12, 0x09, 0x00,0x00,0x00
若s00,定义int在前,char在后; 此时a = 0x12345678, b = 0x09; // 正确,
若s00,定义char在前,int在后,此时b = 0x78, a = 0x09; // 错误,
3. memcpy(c_temp, (char *)&s_temp, sizeof(s_temp)); //最容易出错
本意只想将s_temp的5个字节数据复制到c_temp, 但sizeof = 8, copy了8个字节, 会导致c_temp出错;
此时c_temp[0-9] = 0x09, 0x00,0x00,0x00, 0x78,0x56,0x34,0x12, 0x39, 0x00; // 0x39 = '9'
其他 结构体定义方法
struct 类型名{
成员表列
} 变量;
struct 类型名 变量; typedef struct 类型名{
成员表列
} 别名;
别名 变量;
基本数据类型所占内存大小