Hello All,
In this post I am writing a general approach to designing a memory management system. I am not sharing any code for this and only proposing the overall idea on how to approach this.
Requirements:
Design alloc and free functions for memory management system. Alloc will take the input size and return the memory chunk while free would take the memory chunk and make it available for future use.
Design:
First thing is we need to ensure we do not allocate a bigger chunk of memory for lesser memory requirement. In order to do this, we can divide the available memory into chunks of sizes in powers of 2 and maintain a list of addresses of such sizes. Depending on the conversation with interviwer you can keep a max limit on the largest chunk of memory that you want to support.
[head of memory chunks of size 2] -> [node1] -> [node2]
[head of memory chunks of size 4] -> [node1] -> [node2]
[head of memory chunks of size 8] -> [node1] -> [node2]
If we are to allocate memory based on the size, we need a way to lookup the head of these lists. We can use a hashtable to store the length of memory chunk as key and the head of the lists as value. These should be available at the boot time of the system.
MemorySizeHashTable(memory_size, head_of_list)Each list node should have start address of physical memory, length of data it can hold, flag representing whether the memory is allocated or usable.
Node memory_unit {
long start_address;
int length;
boolean allocated;
}Alloc API: memory_alloc(size)
NodeAddressHashTable(start_address, memory_unit) => Used in free APIFree API: memory_free(start_address, size)
Few cases that should be covered
Bonus points
Summary of data structures used
Node memory_unit {
long start_address;
int length;
int pid;
boolean allocated;
}MemorySizeHashTable(memory_size, head_of_list)
NodeAddressHashTable(start_address, memory_unit)
PS: I came up with this in one of my interviews :)