C++ allocates abnormally large amout memory for variables

后端 未结 9 756
名媛妹妹
名媛妹妹 2020-12-10 14:13

I recently got to know an integer takes 4 bytes from the memory.

First ran this code, and measured the memory usage:

int main()
{
   int *pointer;
         


        
9条回答
  •  再見小時候
    2020-12-10 14:34

    Each time you allocate an int:

    • The memory allocator must give you a 16-byte aligned block of space, because, in general, memory allocation must provide suitable alignment so that the memory can be used for any purpose. Because of this, each allocation typically returns at least 16 bytes, even if less was requested. (The alignment requires may vary from system to to system. And it is conceivable that small allocations could be optimized to use less space. However, experienced programmers know to avoid making many small allocations.)
    • The memory allocator must use some memory to remember how much space was allocated, so that it knows how much there is when free is called. (This might be optimized by combining knowledge of the space used with the delete operator. However, the general memory allocation routines are typically separate from the compiler’s new and delete code.)
    • The memory allocator must use some memory for data structures to organize information about blocks of memory that are allocated and freed. Perhaps these data structures require O(n•log n) space, so that overhead grows when there are many small allocations.

    Another possible effect is that, as memory use grows, the allocator requests and initializes larger chunks from the system. Perhaps the first time you use the initial pool of memory, the allocator requests 16 more pages. The next time, it requests 32. The next time, 64. We do not know how much of the memory that the memory allocator has requested from the system has actually been used to satisfy your requests for int objects.

    Do not dynamically allocate many small objects. Use an array instead.

提交回复
热议问题