Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 255
wlad Avatar asked Dec 12 '25 04:12

wlad


1 Answers

Why does C need to manage its own heap?

It's not actually specified that it needs to, but it needs to implement malloc() and friends the way they are described in the standard. So if there was an OS already providing such an interface, a C implementation could just provide a tiny wrapper.

Is it because the OS will only allow you to allocate and free contiguous memory of a minimum size? And if that's true, what's the reason?

Yes. A typical OS will manage paged memory and map or unmap processes whole pages of memory. The unit of memory that can be "paged" depends on the hardware architecture. You might want to read some details on how memory management units (MMU) work. On architectures without MMU, the operating system might not do anything and a C implementation would just fullfill malloc() requests from a fixed location in physical address space.