RC RANDOM CHAOS

How malloc Batches Syscalls for Speed

· via Hacker News

Original source

What is malloc doing, anyway?

Hacker News →

malloc batches syscalls to avoid expensive kernel transitions. A demonstration shows 1,000 malloc calls for 16-byte blocks trigger only 2 brk syscalls and a single 132 KiB heap expansion—subsequent allocations reuse this pre-allocated space. This strategy pays off dramatically: a naive allocator calling sbrk directly for each request runs 22.7 times slower than malloc.

The implementation manages memory through chunks with headers and free lists. Each allocation reserves 8 bytes (in glibc) for metadata, rounded to 16-byte boundaries for alignment. Freed chunks enter a free list; malloc searches this list and splits or merges chunks as needed to satisfy requests. The article implements a toy allocator step-by-step to illustrate these mechanisms.

Read the full article

Continue reading at Hacker News →

This is an AI-generated summary. Read the original for the full story.