Memory management: memory alignment

Computer memory is a byte (Byte) bits divided in the unit.

The CPU address bus to access the memory, the CPU 64 can handle eight bytes of data, then reads the 8 bytes of data from memory, less waste of frequency, no more use.
image

#include<iostream>
using namespace std;

struct{
    int a;
    bool b;
    int c;
}t={ 10, false, 20 };
int main(){
    cout << "length:" << sizeof(t) << endl;
    cout << "&a:" << &t.a << endl;
    cout << "&b:" << &t.b << endl;
    cout << "&c:" << &t.c << endl;
    return 0;
}
/*运行结果:*/
length:12
&a:0x481004
&b:0x481008
&c:0x48100c

// 如果不考虑内存对齐,结构体变量t所占内存应该为4 + 1 + 4 = 9个字节。
// 考虑到内存对齐,虽然内存对齐b只占用1个字节,但它所在的寻址步长内还剩下3个字节的空间,放不下一个int型的变量了,所以把c放到下一个寻址步长。
// 剩下的3个字节,作为内存填充浪费掉了。

Guess you like

Origin www.cnblogs.com/xiaobaizzz/p/12342291.html