数据结构对齐
数据结构对齐是数据在计算机内存中排列和访问的方式。数据对齐和数据结构填充是两个不同的问题,但彼此相关,统称为数据结构对齐。
数据对齐:数据对齐意味着将数据放入内存中的地址等于字长的倍数。由于 CPU 处理内存的方式,这提高了系统的性能。
数据结构填充:现在,为了对齐数据,可能需要在最后一个数据结构的结尾和下一个数据结构的开头之间插入一些额外的字节,因为数据以固定字大小的倍数放置在内存中。这种插入额外的内存字节以对齐数据称为数据结构填充。
考虑如下所示的结构:
struct
{
char a;
short int b;
int c;
char d;
}
现在我们可能会认为处理器会为这个结构分配内存,如下所示:
在这种情况下分配的总内存为 8 个字节。但这永远不会发生,因为处理器可以以 4 字节的固定字大小访问内存。因此,整数变量 c 不能如上所示分配内存。一个整型变量需要 4 个字节。下面显示了使用填充字节为该结构分配内存的正确方法。
对于上述结构,处理器总共需要 12 个字节来保持数据对齐。
看下面的 C++ 程序:
// CPP program to test
// size of struct
#include
using namespace std;
// first structure
struct test1
{
short s;
int i;
char c;
};
// second structure
struct test2
{
int i;
char c;
short s;
};
// driver program
int main()
{
test1 t1;
test2 t2;
cout << "size of struct test1 is " << sizeof(t1) << "\n";
cout << "size of struct test2 is " << sizeof(t2) << "\n";
return 0;
}
输出:
size of struct test1 is 12
size of struct test2 is 8
对于第一个结构 test1,short 变量占用 2 个字节。现在下一个变量是 int ,它需要 4 个字节。因此,在 short 变量之后添加了 2 个字节的填充。现在,char 变量需要 1 个字节,但将以 4 个字节的字大小访问内存,因此再次添加 3 个字节的填充。因此,总共需要 12 个字节的内存。我们也可以类似地计算第二个结构的填充。两种结构的填充如下所示:
struct test1
{
short s;
// 2 bytes
// 2 padding bytes
int i;
// 4 bytes
char c;
// 1 byte
// 3 padding bytes
};
struct test2
{
int i;
// 4 bytes
char c;
// 1 byte
// 1 padding byte
short s;
// 2 bytes
};
注意:您可以通过按对齐对成员进行排序来最小化为结构分配的内存大小。
参考 :
1) https://en.wikipedia.org/wiki/Data_structure_alignment
2) https://stackoverflow.com/a/119134/6942060