C++ allocates abnormally large amout memory for variables

后端 未结 9 744
名媛妹妹
名媛妹妹 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:45

    Memory for individually allocated dynamic objects is not required to be contiguous. In fact, due to the alignment requirements for new char[N] (namely to be aligned at alignof(std::maxalign_t), which is usually 16), the standard memory allocator might just never bother to return anything but 16-byte aligned memory. So each int allocation actually consumes (at least) 16 bytes. (And further memory may be required by the allocator for internal bookkeeping.)

    The moral is of course that you should be using std::vector(1000000) to get a sensible handle on one million dynamic integers.

提交回复
热议问题