What mechanisms does the malloc()
function use in practice to manage dynamic memory allocation in a program?
What mechanisms does the malloc()
function use in practice to manage dynamic memory allocation in a program?
Briefly:
Your program / process occupies a memory region that ranges from a x
address to a y
address called heap ). All its malloc
s are allocated in this area between x
and y
. It maintains a data structure, let's say a list, which contains all the free spaces in the stack of this process.
When you call malloc
, it looks through this list and looks for a space that is large enough for the size you want to allocate. If you have this size available, it returns a pointer to this space, registers that it will use it and from there your program will use that slice in memory.
When you deallocate by calling free()
, it picks up that used space that will now be freed, unregisters it and now that freed space goes to the list and if there is any new allocation request, / p>
If you call malloc()
and it can not find any large enough space on the stack, it uses syscall brk()
to increase this range. That is, increase address y
and reallocate all old addresses and new y
to be a valid memory range.
brk()
is a syscall , and therefore there is no way to do the same thing in the user layer.
Look for more information about syscall if you want to understand syscall itself.