For an interview question: how would I write new "malloc" and "free" functions? I don't think "using new and delete" would be an acceptable answer or using something similar like LocalAlloc/HeapAlloc
If free() is not used in a program the memory allocated using malloc() will be de-allocated after completion of the execution of the program (included program execution time is relatively small and the program ends normally).
When you no longer need a block that you got with malloc , use the function free to make the block available to be allocated again. The prototype for this function is in stdlib. h .
new is type-safe, malloc returns objects of type void* new throws an exception on error, malloc returns NULL and sets errno. new is an operator and can be overloaded, malloc is a function and cannot be overloaded.
This is called a memory leak. Memory leaks happen when your program loses the address of some bit of dynamically allocated memory before giving it back to the operating system. When this happens, your program can't delete the dynamically allocated memory, because it no longer knows where it is.
Since this is for an interview question, it probably won't have a "right" answer, and they're more interested in your thought process, and your general knowledge surrounding the topic.
You should ask to clarify the requirements, or give a range of answers depending on the situation. Here are some issues to consider:
Simply put,
Your malloc
function should be able to get memory from the operation system and give it to the client(say, your C program) that requests for memory to be allocated dynamically. To implement this, the malloc library usually has many data structures (depending on implementation) - For eg, the malloc
implementation may choose to keep track of free blocks of memory using a linked-list. A more efficient way would be to have a list of linked lists, each containing blocks of a paticular size range.
I happened to work on TCMalloc library, that might help you understand this more clearly
Memory allocation through freelists
Lets say, class 0 is a linked list of free blocks of size 4k, class 1 is a linked list of free blocks of size 8k and so on.
When a call to malloc is made (say, of size 10k), your malloc implementation traverses through the freelist to find out the smallest free block that would satisfy the request (In this case, a 4k block would not be sufficient, so it'll fetch an 8k block, remove it from the freelist, and return it to your program).
Similarly, when a call to free
is made, your implementation(among other things) should reclaim the block from the program and adds it in the appropriate place to one of the freelists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With