Why do successive calls to new[] not allocate contiguous memory?

后端 未结 1 495
春和景丽
春和景丽 2020-12-20 00:26

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 <         


        
相关标签:
1条回答
  • 2020-12-20 00:49

    Because:

    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.)

    2. 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.

    3. 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.)

    4. 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.)

    5. 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.

    0 讨论(0)
提交回复
热议问题