If malloc calls VirtualAlloc() function to allocate memory (which allocates minimum 4Kb), how malloc allocates 4 bytes for int?
How malloc allocates memory less than 4KB?
1.4k views Asked by user3245337 At
2
There are 2 answers
0
On
Application I am working on is internally using malloc.c implementation from Doug Lea (ftp://g.oswego.edu/pub/misc/malloc.c), it is widely used on many platforms.
This implementation is taking memory from system, in case of Windows in 64KB chunks reserved and commited using VirtualAlloc. Then it uses various algorithms and structures to use this memory as efficiently as possible.
I tested allocation of 2 bytes, and from debugger I see that it first pads it to 4 bytes, and puts it into SmallBins - which is a way of handling small memory allocations. In the end I see real memory usage of this allocation is 16bytes. But this is probably platform dependant.
malloc
requests memory from the OS in multiples of the page size (obviously, since the page size is by definition the quantum of allocated memory) and hands it out to you in smaller chunks.That's not different than what all memory allocators do -- in fact, specialized memory allocators (e.g.
Boost.Pool
) that usemalloc
behind the scenes do exactly this once more: they allocate a bigger chunk of memory throughmalloc
and hand it out to you in smaller pieces.