malloc offers a straightforward interface: request a memory block and receive a void pointer to contiguous bytes. After use, free returns the memory to the system. However, the process involves complex kernel interactions.
As a userspace program, malloc requests memory via syscalls, which are costly at approximately 575 ns each. To optimize performance, glibc maintains bookkeeping internally, avoiding expensive syscalls for small allocations. A demonstration showed that allocating 1000 blocks of 16 bytes required only two brk syscalls: one to check the program break and another to grow the heap by 132 KiB.
Subsequent allocations drew from this pre-reserved memory. The program break, managed via brk or sbrk syscalls, defines the heap's end. While a custom bump allocator exists, it proves inefficient, moving the break on every request.
Benchmarks revealed sbrk(16) costs 610 ns, while optimized malloc(16) runs at 26.9 ns, making malloc roughly 22.7 times faster than direct sbrk calls. The kernel manages memory through regions including text, data, BSS, heap, and stack, with the heap growing upward toward the stack. Ultimately, malloc balances syscall overhead with efficient memory management, providing a critical layer between applications and the operating system's kernel.
Source: Hacker News · Summarized by HeadlinesBriefing