A01 — The Internals of malloc: How brk and mmap Work Together

Key Insight: Every block of memory you allocate with malloc is backed by the system making allocation decisions on your behalf.


malloc is Not a System Call

malloc is a glibc (ptmalloc) library function, not a system call.

Bash
Two paths for malloc:

1. brk/sbrk (system call) — small objects (<= 128KB)
2. mmap/munmap (system call) — large objects (> 128KB)

Performance:
  - brk: ~10ns (user-space operation)
  - mmap: ~500ns (system call + TLB miss)

How brk Works

Bash
brk system call adjusts the program break (heap top).
- brk expands heap upward, shrinks downward
- Only the top chunk can shrink
- Freed chunks are not returned to kernel immediately

How mmap Works

Bash
mmap creates anonymous mappings for large allocations.
- Allocates virtual memory, physical pages on demand
- munmap frees entire block at once
- No fragmentation, clean deallocation

malloc's Complete Strategy

Bash
size <= 128KB → brk path (fast, user-space)
size > 128KB → mmap path (system calls, clean)
Threshold adjustable via mallopt(M_MMAP_THRESHOLD)
Last modified: 2024年10月25日

Author

Comments

Write a Reply or Comment

Your email address will not be published.