字节对齐 – 关于结构体占多大内存问题讨论
什么是字节对齐
计算机是以2, 4, 8的倍数的字节块来读写内存
这样可以对基本数据类型的合法地址作出一些限制
要求各种数据类型按照一定的规则在空间上排列
为什么要考虑字节对齐
通常情况编译器帮助我们进行对齐, 不需我们考虑
但是, 我们可以优化程序的运行
并且可以避免某些错误
结构体的字节对齐
-
对于跨平台通信时可能导致结构体大小不同, 导致乱码
需要考虑 统一 字节对齐
-
可以合理的规划空间大小, 节省空间, 提高运行效率
例子如下
#include "stdio.h"
typedef struct s1
{
long double a;//16个字节
int b;//4字节
int c;//4字节
}s1_t;
typedef struct s2
{
int b;//4字节
long double a;//16个字节
int c;//4字节
}s2_t;
int main()
{
s1_t structure1;
printf("address of structure1 : %d\n",&structure1);
printf("address of a : %d\n",&structure1.a);
printf("address of b : %d\n",&structure1.b);
printf("address of c : %d\n",&structure1.c);
printf("size of s1_t : %d\n\n", sizeof(structure1));
s2_t structure2;
printf("address of structure2 : %d\n",&structure2);
printf("address of b : %d\n",&structure2.b);
printf("address of a : %d\n",&structure2.a);
printf("address of c : %d\n",&structure2.c);
printf("size of s2_t : %d\n\n", sizeof(structure2));
return 0;
}
/**
* 程序运行结果如下
*/
PS F:C> gcc .\struct.c
PS F:C> .\a.exe
address of structure1 : 6487552
address of a : 6487552
address of b : 6487568
address of c : 6487572
size of s1_t : 32
address of structure2 : 6487504
address of b : 6487504
address of a : 6487520
address of c : 6487536
size of s2_t : 48
对齐原则
- 总体大小 为 最大成员 的 整数倍
- 每个成员 相对于结构体 首地址 的 偏移量 都是 该成员 大小的 整数倍