为什么连续调用new []不会分配连续的内存? [英] Why do successive calls to new[] not allocate contiguous memory?

查看:259
本文介绍了为什么连续调用new []不会分配连续的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用64位Ubuntu 14.04.这是我的C ++代码,了解如何使用内存.

I am using Ubuntu 14.04 64-bit. Here is my C++ code to see how memory is used.

int main() {
  int **ptr;

  ptr = new int* [2];
  cout << &ptr << " -> " << ptr << endl; 

  for (int r = 1; r <= 2; r++) {
    ptr[r-1] = new int [2 * r];
    cout << &ptr[r-1] << " -> " << ptr[r-1] << endl;

    for (int c = 0; c < 2 * r; c++) {       
        ptr[r-1][c] = r * c;
        cout << &ptr[r-1][c] << " -> " << ptr[r-1][c] << endl;
    }
  }

  return 0;
}

这是我的输出:

0x7fff09faf018 -> 0x1195010
0x1195010 -> 0x1195030
0x1195030 -> 0
0x1195034 -> 1
0x1195018 -> 0x1195050
0x1195050 -> 0
0x1195054 -> 2
0x1195058 -> 4
0x119505c -> 6

我希望操作系统会连续分配内存.因此,ptr [0] [0]将位于0x1195020而不是0x1195030!操作系统在0x1195020-0x119502F,0x1195038-0x0x119504F做什么用?

I expected the OS would allocate memory contiguously. So ptr[0][0] would be at 0x1195020 instead of 0x1195030!? What does OS use at 0x1195020 - 0x119502F, 0x1195038 - 0x0x119504F for?

推荐答案

原因:

  1. 已分配内存的每个块的开始和结尾处都有一些空间通常用于簿记. (特别是,许多分配器发现在其附近存储前/后块的大小或指向它们的指针很有用.)

  1. Some space at the beginning and end of each block of allocated memory is often used for bookkeeping. (In particular, many allocators find it useful to store the size of the preceding/following blocks, or pointers to them, around there.)

内存分配器可以舍入"已分配块的大小,以使其变得更容易.例如,分配7个字节可能会舍入为8个字节,即使不是16或32也是如此.

The memory allocator may "round up" the size of an allocated block to make things easier for it. For instance, an allocation of 7 bytes will likely be rounded up to 8 bytes, if not even 16 or 32.

在不连续的位置可能已经有可用的内存块. (请记住,C运行时可能在main()运行之前就已经进行了一些内存分配.)

Blocks of memory may already be available in noncontiguous locations. (Keep in mind that the C runtime may have been making some memory allocations of its own before main() even runs.)

分配器可能有一个规划内存的计划,该计划可能由于将下一个块放在下一个"地址而被破坏. (例如,它可能已保留该内存用于特定大小的分配.)

The allocator may have a plan in mind for laying out memory which would be ruined by putting the next block at the "next" address. (It may, for instance, have reserved that memory for allocations of a particular size.)

为什么要这么做?没有任何保证.分配的内存可能会终止在任何地方. (好吧,几乎.)不要做任何假设,只要让内存转到分配器表示将要到达的位置,就可以了.

Why should it? There are no guarantees. Allocated memory could end up anywhere. (Well, almost.) Don't make any assumptions, just let memory go wherever the allocator says it'll go, and you'll be fine.

这篇关于为什么连续调用new []不会分配连续的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆