What is malloc doing, anyway?
Web page · https://benmandrew.com/articles/what-is-malloc-doing-anyway
First seen by Oriel on .
AI summary
This article builds a toy C allocator to explain how glibc malloc amortizes syscalls, manages reusable chunks, uses demand paging, and returns memory through heap trimming or mmap and munmap.
- In the example, 1,000 malloc(16) calls trigger two brk calls and one 132 KiB heap growth; malloc averages 26.9 ns versus 610.1 ns for sbrk(16).
- glibc adds an 8-byte size header, rounds chunks to 16-byte multiples with a 32-byte minimum, and reuses freed payload space for free-list pointers.
- The toy allocator grows by 64 KiB, splits suitable free chunks, coalesces adjacent freed chunks, and trims top-of-heap space after it reaches 128 KiB.
- Demand paging lets sbrk reserve 1 GiB virtually without equivalent RAM; writing each 256 MiB causes 65,536 page faults and raises RSS accordingly.
- Requests of at least 128 KiB receive page-rounded anonymous mmap mappings, allowing munmap despite adjacent live chunks; however, separate mappings cannot coalesce across gaps.
#c #glibc #memory allocation #virtual memory
Generated by gpt-5.6-sol. Check the original for details.
Metric trends
Last 30 days · Up to 120 recorded samples per source and metric, with reposts kept separate · First and latest retained
Points
Score reported by the source.
- Hacker News: 253, latest observation ; +245 over observed period since
- Lobsters: 19, latest observation ; +17 over observed period since
Comments
Comment count reported by the source.
- Hacker News: 64, latest observation ; +64 over observed period since
- Lobsters: 3, latest observation ; +2 over observed period since
Aliases
| Source | External ID | URL |
|---|---|---|
| Hacker News | 50424157 | https://benmandrew.com/articles/what-is-malloc-doing-anyway Read discussion |
| Lobsters | l75lxf | https://benmandrew.com/articles/what-is-malloc-doing-anyway Read discussion |