为什么new第一次会多分配1040字节?

Why does new allocate 1040 extra bytes the first time?

我正在创建这个简单的测试程序来演示使用标准 new 分配内存时对齐的工作方式...

#include <iostream>
#include <iomanip>
#include <cstdint>

//
// Print a reserved block: its asked size, its start address 
//       and the size of the previous reserved block
//
void print(uint16_t num, uint16_t size_asked, uint8_t* p) {
   static uint8_t* last = nullptr;

   std::cout << "BLOCK " << num << ":   ";
   std::cout << std::setfill('0') << std::setw(2) << size_asked << "b, "; 
   std::cout << std::hex << (void*)p;
   if (last != nullptr) {
      std::cout << ", " << std::dec << (uint32_t)(p - last) << "b";
   }
   std::cout << "\n";
   last = p;
}

int main(void) {
   // Sizes of the blocks to be reserved and pointers
   uint16_t s[8] = { 8, 8, 16, 16, 4, 4, 6, 6 };
   uint8_t* p[8];

   // Reserve some consecutive memory blocks and print
   // pointers (start) and their real sizes
//   std::cout << "          size   start    prev.size\n";
//   std::cout << "-----------------------------------\n";
   for(uint16_t i = 0; i < 8; ++i) {
      p[i] = new uint8_t[s[i]];
      print(i, s[i], p[i]);
   }

   return 0;
}

但是当我执行程序时,我发现了这个奇怪的行为:

[memtest]$ g++ -O2 mem.cpp -o mem
[memtest]$ ./mem 
BLOCK 0:   08b, 0xa0ec20
BLOCK 1:   08b, 0xa0f050, 1072b
BLOCK 2:   16b, 0xa0f070, 32b
BLOCK 3:   16b, 0xa0f090, 32b
BLOCK 4:   04b, 0xa0f0b0, 32b
BLOCK 5:   04b, 0xa0f0d0, 32b
BLOCK 6:   06b, 0xa0f0f0, 32b
BLOCK 7:   06b, 0xa0f110, 32b

如你所见,new分配的第二个块不在下一个32b内存对齐地址,而是在很远的地方(1040字节)。如果这还不够奇怪,取消注释打印出 table 的 header 的 2 std::cout 行会产生以下结果:

[memtest]$ g++ -O2 mem.cpp -o mem
[memtest]$ ./mem 
          size   start    prev.size
-----------------------------------
BLOCK 0:   08b, 0x1f47030
BLOCK 1:   08b, 0x1f47050, 32b
BLOCK 2:   16b, 0x1f47070, 32b
BLOCK 3:   16b, 0x1f47090, 32b
BLOCK 4:   04b, 0x1f470b0, 32b
BLOCK 5:   04b, 0x1f470d0, 32b
BLOCK 6:   06b, 0x1f470f0, 32b
BLOCK 7:   06b, 0x1f47110, 32b

这是正常的预期结果。是什么让 new 一开始表现得如此奇怪 运行?我使用的是 g++ (GCC) 7.1.1 20170516。你可以在没有优化的情况下编译,结果是一样的。

很多东西,包括 << 的流重载,都使用与“new”相同的堆。

有些 运行 次将分配随机化,以此作为减缓破解者尝试缓冲运行 恶作剧的一种方式。

new不保证内存块是连续的。

此外,我鼓励您阅读有关 Fragmentation 的内容,这很可能是正在发生的事情,系统会尝试填补漏洞。

您会惊讶地发现,您的程序所做的不仅仅是进行一些内存分配。

std::cout << "BLOCK " << num << ":   ";

您的程序还利用其内置 std::streambuf.

生成格式化输出到 std::cout

很明显,std::cout 的第一个输出为内部 std::streambuf 分配了一个 1024 字节的缓冲区。这发生在您的第一个 new 分配之后和第二个分配之前。缓冲区只需要在第一次使用时分配一次。

虽然不用说内部内存分配的细节是高度实现定义的,但这似乎是您的情况最可能的解释。