Johnny Pauling Johnny Pauling - 1 month ago 8
C Question

Writing new "malloc" and "free" functions

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

Answer

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:

  • Is it important to avoid memory fragmentation? A fixed alloc size may help.
  • Do you need speed guarantees for allocation? Use index of used/free blocks.
  • Do you need to easily trace the allocations performed? Add logging structures to the malloc/free library.
  • Do you need to protect against or detect memory under/overruns? Extra padding and periodic padding checks.