How does malloc obtain memory from the heap?

Viewed 122

We know that malloc calls mmap internally. But mmap doesn't necessarily map to the heap as mmap can map objects to any area in virtual memory, then how does malloc do internally to make sure that the requested size of memory is from the heap?

1 Answers

When malloc uses mmap to allocate memory, it doesn‘t care where the memory comes from — it delegates the allocation to mmap, and relies on that to provide a usable block of memory.

In the GNU C library (and probably in other implementations too), such allocations are tracked separately from the allocations managed using sbrk. All operations involving mmaped allocations are also delegated (reallocation and freeing).

From the kernel’s perspective, such allocations are off-heap, i.e. after the program break. From the programmer’s perspective, they’re all the same; the main practical consequences compared to sbrk-only allocations is that you can’t assume that allocated blocks are within the program break, or that the address space between two allocated blocks is accessible, but you shouldn‘t do that anyway.

See also the POSIX specification for malloc — it doesn’t say anything about the heap.

Related