What is malloc doing, anyway? benmandrew.com · 29 points · 3 comments · HN threa...

@best

What is malloc doing, anyway? benmandrew.com · 29 points · 3 comments · HN thread

TL;DR The article walks through how glibc malloc works by building up a toy allocator in stages: a bump allocator on sbrk, then chunk headers, a free list with splitting and coalescing, trimming the heap, and mmap for large blocks. It measures each stage against glibc, which is roughly 65 to 142 times faster than the toy versions with free lists, mainly because of bins and a thread-local tcache.

  • A single malloc(16) loop makes only two brk syscalls, since the first malloc grows the heap by 132 KiB and the other 999 calls are served from it.
  • A syscall costs about 575 ns on the test machine, while malloc(16) takes about 27 ns, so malloc keeps bookkeeping in userspace.
  • glibc stores an 8-byte size header before each chunk, rounds chunks to multiples of 16 with a 32-byte minimum, and uses spare bits for flags including M for mmapped chunks.
  • Freed memory stays resident until the allocator returns it; trim lowers the break only from the top of the heap, so fragmentation can keep RSS high.
  • Requests of 128 KiB or more can get their own mmap mapping, which is released immediately on free. glibc makes 51 mmap calls in the benchmark versus 5040 for the toy allocator.
  • In the benchmark, glibc takes 0.0789 µs per step, against 5.12 µs for the free-list allocator and 11.2 µs for the trimming version, mainly due to bins and the tcache.

Discussion The comment thread is very small, with only three comments. One commenter links the article's topic to stack-only languages like Goose, suggesting that dropping heap allocation could remove much of malloc's complexity. A reply corrects the premise: a stack is itself a bump allocator, and what distinguishes such languages is lifetime management rather than allocation strategy. The mood is brief and mostly neutral, with a single off-topic remark about DRAM scarcity.

  • Stack-only languages could make heap allocation largely unnecessary (some): One commenter finds the complexity of malloc a reason to be interested in stack-only languages such as Goose, and hopes that language ergonomics can replace heap-allocated memory as garbage collectors were replaced.
  • Stack-only languages are about lifetimes, not allocation (some): A reply notes that the stack is already a bump allocator, so the distinctive part of stack-only languages is how they manage object lifetimes, not how they allocate.
  • Memory economics may make the topic matter less (a few): One commenter says that if DRAM scarcity continues, the allocator details will not matter much, without elaborating.

#malloc #glibc #memoryAllocation #systemsProgramming #linux