研究字节对齐
今天花了半天好好研读了一下微软这篇文章,基本搞明白了字节对齐。Alignment
Alignment is a property of a memory address, expressed as the numeric address modulo a power of 2 [reference]. For example, the address 0x0001103F modulo 4 is 3. That address is said to be aligned to 4n+3, where 4 indicates the chosen power of 2. The alignment of an address depends on the chosen power of 2. The same address modulo 8 is 7. An address is said to be aligned to X if its alignment is Xn+0.
这段话得仔细理解一下:Alignment是内存地址的一个属性,这个属性以把内存地址视为对2的幂进行取模运算的形式来表达。 例如,地址0x0001103F模4得3,则我们说这个地址是对齐到4n+3的,即该地址的Alignment是4n+3,其中4就是2的2次幂。内存地址的对齐属性依赖于对2的幂的选定。 同样这个地址,模8则得7,我们就说该地址的Alignment是8n+7。 结论:一个地址我们说它对齐到(Aligned to)X,如果它的Alignment是Xn+0
这里又有个【自然对齐】的概念,即naturally aligned。 自然对齐说的是数据的地址对齐到这个数据的尺寸。联系上一段的结论来解释自然对齐,就是:如果一个地址的Alignment是DataSize*n+0,则该地址对齐到DataSize,且称此时为自然对齐。 注意此时2的幂的选定结果是DataSize。比如,如果一块8字节浮点数据的地址的Alignment是8*n+0,则该地址是自然对齐的。
struct x_
{
char a; // 1 byte
int b; // 4 bytes
short c; // 2 bytes
char d; // 1 byte
} bar[3];
// Shows the actual memory layout
struct x_
{
char a; // 1 byte
char _pad0[3]; // padding to put 'b' on 4-byte boundary
int b; // 4 bytes
short c; // 2 bytes
char d; // 1 byte
char _pad1[1]; // padding to make sizeof(x_) multiple of 4
} bar[3];
struct x_
{
char a; // 1 byte
int b; // 4 bytes
char c;// 1byte
};
struct x_
{
char a; // 1 byte
char _pad0[3]; // 3 bytes
int b; // 4 bytes
char c;// 1 byte
char _pad1[3]
};
struct m_
{
char a; // 1 byte
double b; // 8 bytes
char c; // 1 byte
};