Dan*_*nny 6 c++ memory alignment
我测试了这段代码,试图找出为新运算符实际保留了多少内存c ++.
#include<iostream>
using namespace std;
int main() {
cout << "alignment of " << alignof(int) << endl;
int *intP1 = new int;
*intP1 = 100;
cout << "address of intP1 " << intP1 << endl;
int *intP2 = new int;
*intP2 = 999;
cout << "address of intP2 " << intP2 << endl;
int *intP3 = new int;
cout << "address of intP3 " << intP3 << endl;
*intP3 = 333;
cout << endl;
cout << (reinterpret_cast<char *>(intP3)-reinterpret_cast<char *>(intP2)) << endl;
cout << intP3-intP2 << endl;
cout << endl;
cout << *(intP1) << endl;
cout << *(intP1+4) << endl;
cout << *(intP1+8) << endl;
cout << *(intP1+16) << endl;
delete intP1;
delete intP2;
delete intP3;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在使用-std = c ++ 11标志编译代码并运行它之后,这是我从x86_64机器获得的.
alignment of int4
address of intP1 = 0xa59010
address of intP2 = 0xa59030
address of intP3 = 0xa59050
the distance of intP3 and intP2 = 32
intP1 value = 100
is this a padding value = 0
intP2 value = 999
intP3 value = 333
Run Code Online (Sandbox Code Playgroud)
似乎当使用new为一个整数分配一个4字节的内存时,它实际上保留了32个字节的块,这是8个整数的总空间.根据c ++对齐的解释,对于64位机器,内存在16个字节上对齐,为什么这里的距离是32个字节?
有人可以帮我解决这个问题吗?提前致谢.
它与对齐无关 - 它是内部内存分配器工作方式的额外开销.通常,每个内存块在其前面和/或后面都有额外的隐藏信息,用于维护堆的结构.究竟有多少开销会因平台和实现而异.
例如,Doug Lea的malloc额外开销为每个分配4-8个字节(32位指针)或8-16个字节(64位指针),最小分配大小为16个字节(32位)或32个字节( 64位).这意味着即使是1字节的分配,内存分配器也需要总共16个字节的跟踪开销.