Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How malloc allocates memory less than 4KB?

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

like image 635
user3245337 Avatar asked Jan 11 '23 08:01

user3245337


1 Answers

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.

like image 78
Jon Avatar answered Jan 20 '23 01:01

Jon