If malloc calls VirtualAlloc() function to allocate memory (which allocates minimum 4Kb), how malloc allocates 4 bytes for int?

有帮助吗?

解决方案

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 use malloc behind the scenes do exactly this once more: they allocate a bigger chunk of memory through malloc and hand it out to you in smaller pieces.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top