关于内存对齐的计算和几个例子
对齐规则介绍(23.10.13修改:符合在msvc中的表现)
pragma pack(n)为对齐单位,
min(对齐单位,结构体中最大的数据成员的大小)为有效对齐值
结构体中每个数据成员的首地址相对结构体初始地址的偏移值 为 min(该成员大小,有效对齐值)的整倍数
结构体的总大小为有效对齐值的整倍数
原测试代码
#include <iostream>
#pragma pack(8)
using namespace std;
class noV
{
char z;
int k;
double y;
};
class hasV:public noV
{
virtual void vP() { cout << "xV" << endl; };
};
struct XD1
{
int i;
char c1;
char c2;
}x1;
struct {
char c1;
int i;
char c2;
}x2;
struct {
char c1;
char c2;
int i;
}x3;
int main()
{
cout << sizeof(noV) << endl;
cout << sizeof(hasV) << endl;
void* ptr = nullptr;
cout << sizeof(ptr) << endl;
short snum = 0;
cout << sizeof(snum) << endl;
//16 , 24 , 8 , 2
XD1 xd1;
cout << "div\n";
cout << sizeof(x1) << endl;
cout << sizeof(x2) << endl;
cout << sizeof(x3) << endl;
return 0;
}
参考资料:C/C++内存对齐详解
关于对默认对齐数错误认知的纠正
通常来讲网络可检索的中文面试资料大多宣称linux下默认对齐数为4,
但根据我进一步检索,发现一篇优质文章Linux gcc没有默认对齐数(内赋gcc官方大佬邮件)
根据我个人的测试代码与文章相照应,确定了至少笔者(gcc9.4)与文章作者的编译器(4.8)中,没有默认对齐数的事实。
实际对齐规则为:对齐到该类型大小的整数倍处
23.10.13修正
#include <iostream>
//#pragma pack(8)
struct test
{
char a;
long double b;
char c;
};
int main(void)
{
std::cout << sizeof(test) << std::endl;
return 0;
}
//假定该版本默认对齐数是4, &a=0,&b=4,&c=12, last 为4的倍数,sizeof test =16
//假定该版本默认对齐数是8, &a=0,&b=8,&c=16, last 为8的倍数,sizeof test =24
//假定该版本默认对齐数是1, &a=0,&b=1,&c=9, last 为1的倍数,sizeof test =10
//假定该版本默认对齐数是4, &a=0,&b=4,&c=20, last 为4的倍数,sizeof test =24
//假定该版本默认对齐数是8, &a=0,&b=8,&c=24, last 为8的倍数,sizeof test =32
//假定该版本默认对齐数是16, &a=0,&b=16,&c=32, last 为8的倍数,sizeof test =48
//假定该版本默认对齐数是1, &a=0,&b=1,&c=17, last 为1的倍数,sizeof test =18

浙公网安备 33010602011771号