malloc barely touches the kernel: 1,000 allocations, just two syscalls
What is malloc doing, anyway?
A hands-on walkthrough of what malloc actually does under glibc: it asks the kernel for memory via brk, grabs a 132 KiB heap chunk on the first call, and serves the next 999 allocations from that pool. The post then builds a toy allocator step by step—adding chunk headers, free lists, splitting and coalescing, demand paging, and finally trimming memory back to the kernel—while timing syscalls to show why malloc(16) runs 22.7 times faster than sbrk(16).
Each 256 MiB written then costs 65,536 page faults, one per 4 KiB page, increasing the RSS.
- assumed_throwaw
Tangential, but the complexity and over-head of the malloc abstraction is precisely what made me very intrigued by "stack-only" languages, such a recently published Goose. There is something very elegant and exciting about the idea of (almost) completely getting rid of it. Just as modern programming languages have developed good ergonomics that replaces a garbage collector, the same could hopefully be done to replace heap-allocated memory.
- K0IN
When getting into wasm when it was new and had clang support, I wrote my own libc and malloc, which was so a great learning all these low level functions and tricks (free lists for example), I also like that I can read wasm quite well, and tooling is good to just return a .wat and read it.
- projectileboy
Good learning resource for this (and related) topics: https://cs61.seas.harvard.edu/site/2026/
- bajard
Malloc() is sloooow. Even more if you also use free(). Consider allocating a single array and scratching there if possible.
- wpmaven
I found this one very well explained time ago, for those looking for more details: https://sploitfun.wordpress.com/2015/02/10/understanding-gli...