C++ allocates abnormally large amout memory for variables -


i got know integer takes 4 bytes memory.

first ran code, , measured memory usage:

int main() {    int *pointer; } 

enter image description here

  • it took 144kb.

then modified code allocate 1000 integer variables.

int main() {    int *pointer;     (int n=0; n < 1000; n++)      {         pointer = new int ;       } } 

enter image description here

  • then took (168-144=) 24kb
    but 1000 integers suppose occupy (4bytes x 1000=) 3.9kb.

then decided make 262,144 integer variables should consume 1mb of memory.

int main() {    int *pointer;     (int n=0; n < 262144; n++)      {         pointer = new int ;       } } 

surprisingly, takes 8mb

enter image description here

memory usage, exponentially grows respective number of integers.
why happening?

i'm on kubuntu 13.04 (amd64)
please give me little explanation. thanks!

note: sizeof(integer) returns 4

memory individually allocated dynamic objects not required contiguous. in fact, due alignment requirements new char[n] (namely aligned @ alignof(std::maxalign_t), 16), standard memory allocator might never bother return but 16-byte aligned memory. each int allocation consumes (at least) 16 bytes. (and further memory may required allocator internal bookkeeping.)

the moral of course should using std::vector<int>(1000000) sensible handle on 1 million dynamic integers.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -