我测试这段代码只是想找出 c++ 实际为 new 运算符保留了多少内存。
#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;
}
在使用 -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
似乎在使用new为一个整数分配4字节的内存时,它实际上预留了32字节的 block ,这是8个整数的总空间。根据c++对齐的解释,对于64位机器,内存是按16字节对齐的,为什么这里的距离是32字节?
有人可以帮我解决这个问题吗?提前致谢。
最佳答案
它与对齐无关——它是内部内存分配器工作方式的额外开销。通常,每个内存块在前面和/或后面都有额外的隐藏信息,用于维护堆的结构。究竟有多少开销会因平台和实现而异。
例如,Doug Lea's malloc
每个分配有 4-8 字节(32 位指针)或 8-16 字节(64 位指针)的额外开销,最小分配大小为 16 字节(32 位)或 32 字节(64 位)。这意味着即使是 1 字节的分配,内存分配器也需要总共 16 字节的跟踪开销。
关于c++ - C++内存对齐是正确的还是低效的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13370718/