Search code examples
cheap-memorydynamic-memory-allocationvirtual-memory

Why does C manage the heap, instead of the operating system?


In other words, why doesn't free() just return the memory to the operating system, and malloc simply request memory from the operating system?

This unpacks to three closely related questions:

  • Why does C need to manage its own heap? (Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size?)
  • Assuming what I wrote in parentheses is true, why is it?
  • Can this problem affect the operating system itself, so that it's unable to allocate blocks of memory to any running processes?

Solution

    1. malloc is a C method itself. You are using a standard library that provides it for you, but in the end, it is C code just like yours is.
    2. In some operating systems, you can only get memory from the OS in the size of pages (using mmap). This is too big for your regular data structure.
    3. Doing a system call every time you need memory is way too expensive.