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:
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?)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.
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