How malloc Works
The heap and free lists.
What malloc Really Does
When you call malloc(n), the C library hands you a pointer to at least n usable bytes. But the heap is just a region of process memory the allocator manages on your behalf.
The allocator's job is bookkeeping: tracking which bytes are in use, which are free, and how to reuse freed memory efficiently.
The Heap Comes from the OS
The allocator does not create memory from nothing. It asks the operating system for large chunks via system calls like brk/sbrk or mmap.
Then it carves those chunks into smaller blocks for your malloc calls. Asking the OS is expensive, so allocators request memory in bulk and recycle it.
/* Conceptual: grow the heap by 4096 bytes */
void *base = sbrk(4096);
if (base == (void *)-1) {
/* out of memory */
}