What malloc does behind the scenes in glibc
The article explains what malloc does behind the scenes in GNU libc (glibc). A program that calls malloc(16) a thousand times makes only two brk syscalls[1], and both happen during the first call; the other 999 calls take memory that is already allocated. An empty syscall takes 575 ns, so malloc asks the kernel for large blocks and divides them itself.
The author builds a bump allocator[2] that moves the program break[3] on every request. Each move is a syscall, and sbrk(16) costs 610.1 ns per call against 26.9 ns for malloc(16), which is 22.7 times faster. This allocator also cannot reuse freed memory, so each new request goes after the previous one.
Each allocation, or chunk, has an 8-byte size header just before the returned pointer, and chunk sizes are multiples of 16 with a minimum of 32. When a chunk is freed, it goes onto a free list[4]; malloc splits large chunks to fit small requests, and free merges free neighbours back together.
Read the original benmandrew.comDiscussion
Discussion
Readers call the article a good introduction to memory allocation. Several commenters note that brk-based allocation is obsolete compared with mmap-based allocators such as jemalloc and mimalloc, and they suggest further resources, including the binary buddy scheme and Knuth's books.
Sources
-
benmandrew.com
What is malloc doing, anyway?
-
KRGeekNews KO
malloc은 대체 무슨 일을 할까?


