One of the many functions of an Operating System is to manage the memory, and distribute them amongst running processes and threads.
The operating system does this by having a pool of memory, that means unused memory, then assign memory from the pool to any program/process that request for it.
This act of assigning memory from the pool, to the program/process is called memory allocation
Two method of memory allocation
- Direct Memory Mapping
This method directly notify the operating system that you need an amount of RAM, and the operating system would assign it to you.
The disadvantage of this is that system call ( direct notification to the operating system ) is an expensive process, as in it is slow. Further more, there are often restrictions that one have to allocate to page size, or it will be rounded up to page boundary. ( Normal page size is 4k on x86 CPU if I am not wrong. ) Another advantage is that you get to set the I/O privilege of the pages.
Example of implementation:
mmap(); // POSIX
VirtualAlloc(); // Windows
Allocate from heap
This method is to preallocate a few page ( called the program heap ), then whenever a request for memory is issued, it will see if the free space in heap is big enough to fulfill the request. If it is, then it will directly assign those memory from the heap to the program. Otherwise, it will allocate more page, then assign the memory. Note that this method happens outside of the Operating System.
Disadvantage is that there’s an extra layer, and does not allow you to specify the I/O privilege of the pages that you are allocating. The advantage is that one can allocate any size of memory, without the limitation of page size. Also, it is faster, as most of the time it doesn’t involve in system calls.
Exampe of implementation:
mallloc(); // ANSI C