c++ - C++内存对齐是正确的还是低效的?

标签 c++ memory alignment

我测试这段代码只是想找出 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/

相关文章:

c++ - 访问 tr1/unordered_map 的内在类型哈希函数

c++ - 获取 GDB 便利变量中保存的值的符号信息

windows - Realloc() 在 Windows 中没有正确释放内存

c++ - 程序在释放 vector 时收到 `SIGTRAP`

javascript - 当多个 div 干扰其对齐时如何对齐 div

java - 将 int 转换为 string 时对齐 Decimal

c++:在多线程程序中写入文件

c++ - 从 Visual Studio 2012 使用 GnuTLS 3.1.6 时获取 "error LNK2001: unresolved external symbol _gnutls_free"

memory - UNIX 和 Linux 和 Windows 的进程内存限制和地址空间

html - div 和 ul 之间奇怪的垂直空间