Memory management in Linux(Buddy algorithms)
Memory allocators have two distinct tasks. First, the memory allocator uses the sbrk() system call to ask the operating system to expand the heap segment of the its virtual address space. However in the code we’ve provided, we use mmap() to simulate a process’s heap in the memory-mapped segment. Second, the memory allocator manages this memory by maintaining the internal structure of the heap including tracking the size and status of each block. When the process makes a request for heap memory, the allocator searches its list of heap blocks for one that is large enough to satisfy the request. The chosen block may be split into two smaller ones before having its status set to allocated. Later when process frees memory, the allocator changes the block’s status to freed and may coalesce it with free neighbors to make larger blocks.
This memory allocator is usually provided as part of a standard library rather than being part of the operating system. Thus, the memory allocator operates entirely within the virtual address space of a single process and knows nothing about which physical memory pages have been allocated to this process or the mapping from virtual addresses to physical addresses.(Virtulization)
The C programming language defines its allocator with the functions malloc() and free() found in “stdlib.h”.
How free & malloc works
Memory management unit control a list of memory and mark each block of memory as used/free, besides, it maintains a header of memory block and alloc memory using this pointer.
Note that for improved performance, Mem_Init(int sizeOfRegion) rounds up the amount memory requested to the nearest page so it is possible that more memory might be allocated than originally specified by sizeOfRegion. All of this memory is initialized as the first and only block in the free list to be used by your allocator and is accessed via first_block, which will be pointing to that block’s header. This is the beginning of the implicit free list that your allocator uses to allocate blocks via Mem_Alloc() calls. Your allocator will need to divide this block into smaller pieces as memory is requested.
Note, we won’t request more memory from the OS than what was originally allocated by Mem_Init().