Tracing a 4 GiB Allocation, Swap Stalls, and the Cost of Inlining
System DesignModel answerLast updated
Walk through how a huge allocation becomes virtual and physical memory on Linux, why swap hurts tail latency, and what C++ inline means for linkage and the CPU.
Memory, Paging, and Inlining in a Latency-Sensitive C++ Service
You are building a C++ service on Linux whose hot loop must finish in a few microseconds, with a very tight 99.99th-percentile latency. Answer the three parts below, and be specific about syscalls, thresholds, and rough costs.
Part 1: What happens on a 4 GiB allocation
Your program runs std::vector<char> buf(4ULL << 30); or malloc(4ULL << 30).
- How does the allocator choose between extending the heap with
brk/sbrkand creating an anonymousmmapregion? - What does the kernel hand back right away? How do virtual address space and physical RAM differ at that moment?
- Distinguish minor from major page faults. Compare filling the buffer sequentially with touching it sparsely.
Part 2: Memory pressure, swap, and tail latency
- How does the kernel's reclaim logic treat anonymous pages versus file-backed page-cache pages?
- What is thrashing, and why can one swapped-out page turn a microsecond-scale loop iteration into a multi-millisecond outlier?
- Compare turning swap off entirely with using
mlock/mlockall. What does each guarantee, and what does each leave open?
Part 3: inline in C++
- What is the language-level purpose of
inline, particularly with respect to the One Definition Rule across translation units? - How do GCC and Clang actually treat the keyword when optimizing? How does link-time optimization (LTO) change whether you need it?
- Discuss the hardware costs and benefits of aggressive inlining: L1 instruction cache footprint, register allocation and spilling, and branch prediction.
Give a structured answer with trade-offs, and point out common misconceptions.
Hints
Hint 1
For Part 1, ask whether `std::vector` merely reserves memory or also writes to it, and compare that with plain `malloc`. Then count how many 4 KiB pages are in 4 GiB.
Hint 2
For Part 2, list what the kernel can do with a page when it needs the frame back: drop it, write it out then drop it, or nothing. Then ask which of those is possible for your own executable's code if swap is off.
Hint 3
For Part 3, separate what `inline` means to the linker from what it means to the optimizer. For the hardware side, think of three separate resources that get stressed when code is duplicated at many call sites.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
This question has no algorithm. It tests whether you can follow an abstraction down to the kernel and the CPU. The three traps to catch are:
std::vectorwrites zeros, so it touches every page.- Turning swap off does not eliminate major faults.
inlineis about linkage, not speed.
Part 1: A 4 GiB allocation
Choosing brk or mmap. glibc's malloc compares the size to M_MMAP_THRESHOLD. It defaults to 128 KiB and adapts upward after frees, with a ceiling of 32 MiB on 64-bit systems. Anything larger bypasses the heap arenas. 4 GiB is far above the ceiling, so glibc issues an anonymous private mapping directly, roughly mmap(NULL, size + header, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0).
Large blocks avoid brk for two reasons:
- The
brkheap is one contiguous region, so a big block can get stranded by fragmentation. - An
mmapchunk goes back to the OS withmunmaponfree.
What the kernel returns. The kernel runs the overcommit check governed by vm.overcommit_memory. Mode 0 uses a heuristic that rejects clearly impossible requests, and mode 2 enforces a strict commit limit. It then creates a VMA (virtual memory area) for the range and returns the address. There are no page-table entries and no physical frames yet, and RSS does not change. The call costs about the same for 4 KiB or 4 GiB.
The std::vector trap. std::vector<char> buf(N) value-initializes its elements, which amounts to a memset of zero over all 4 GiB. Every page is touched immediately and the whole amount becomes resident. Plain malloc does not touch the pages. calloc on a fresh mmap chunk can skip the memset because the kernel already supplies zeroed pages.
Minor and major faults. The first access to an untouched anonymous page traps into the kernel.
- A first read maps the shared read-only zero page.
- A first write allocates a frame, zeroes it, and installs a writable PTE.
Both are minor faults. They need no disk I/O and cost roughly 0.5 to 2 µs each, including zeroing.
- Sequential fill: 4 GiB / 4 KiB is 1,048,576 faults, on the order of one to two seconds of kernel time. With Transparent Huge Pages this drops to about 2,048 faults of 2 MiB.
- Sparse touch: Only touched pages fault, so RSS stays small. However, each first touch charges a fault to whatever code path performs it.
- Major faults: These happen when the data must come from a block device, such as a swapped-out anonymous page or an evicted file page. They cost tens to hundreds of µs or more.
To keep faults off the hot path, prefault at startup with MAP_POPULATE, madvise(MADV_POPULATE_WRITE), or by writing one byte per page.
Part 2: Swap and tail latency
Anonymous versus file-backed pages. Reclaim works from LRU lists split into anonymous and file lists (or MGLRU generations on newer kernels).
| Page type | Reclaim behavior |
|---|---|
| Clean file-backed (page cache, program text, mapped files) | Dropped, re-read from the file on demand |
| Dirty file-backed | Written back, then dropped |
| Anonymous (heap, stack) | Needs swap space to be evicted. With no swap it cannot be reclaimed |
vm.swappiness shifts the balance between the two lists. kswapd reclaims in the background once free memory falls under the low watermark. If memory drops under the min watermark, the allocating thread does direct reclaim and blocks until it finishes.
Thrashing. When the working set exceeds RAM, the kernel evicts pages that are needed again almost immediately. Each refault evicts another useful page, the CPU waits on I/O, and throughput collapses.
A single swapped-out page on the critical path costs:
- a major fault,
- a block I/O request (NVMe about 50 to 100 µs, SATA SSD hundreds of µs, spinning disk 5 to 10 ms),
- queueing behind other swap traffic,
- possible contention on the address-space lock,
- descheduling of the thread and wakeup latency afterward.
A loop that normally takes about 2 µs can then show a p99.99 in the milliseconds, three or more orders of magnitude worse. It is also unpredictable, which is the real damage for a deterministic system.
Swap off versus mlock/mlockall.
Disabling swap:
- Anonymous pages can no longer be evicted.
- File pages can still be dropped, including your own binary's code and shared libraries, so major faults on code remain possible under pressure.
- Severe pressure ends in the OOM killer instead of slow degradation.
mlockall(MCL_CURRENT | MCL_FUTURE):
- Pins all current mappings, anonymous and file-backed, and prefaults them. With
MCL_FUTURE, later mappings are populated when they are created. - Needs
CAP_IPC_LOCKor a sufficientRLIMIT_MEMLOCK. - Costs: locked memory is unavailable to other processes, and allocations fail once the limit is reached.
- It does not necessarily stop page migration or compaction, which can be controlled via
vm.compact_unevictable_allowed.
The usual production recipe is mlockall, prefault and preallocate pools at startup, and no allocation on the hot path.
#include <sys/mman.h>
#include <cstdlib>
void* reserve_hot(std::size_t n) {
if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) std::abort();
void* p = mmap(nullptr, n, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE, -1, 0);
if (p == MAP_FAILED) std::abort();
return p; // resident, locked, zeroed
}
Part 3: inline
Language meaning. inline relaxes the One Definition Rule. It allows the same function definition to appear in several translation units, which is why header-defined functions work. The program still behaves as if there were one function with one address. Member functions defined inside a class body are implicitly inline, constexpr functions are too, and C++17 added inline variables.
Compiler behavior. GCC and Clang decide using a cost model: callee size, call-site hotness, profile data, and whether arguments are constants. The keyword is at most a mild hint (Clang adds an inlinehint attribute, and GCC slightly raises its size threshold). Inline functions are emitted as COMDAT/weak symbols that the linker deduplicates. With LTO or ThinLTO, the optimizer sees all translation units and can inline across .cpp files, so the keyword has almost no optimization role. It stays necessary purely for ODR correctness. To force the issue you would use __attribute__((always_inline)) or noinline, and sparingly.
Hardware trade-offs.
Benefits:
- No call/return overhead or caller-saved register traffic.
- Enables constant propagation, devirtualization, dead-code removal, and vectorization across the former boundary.
Costs:
- L1i footprint: Duplicating a body at many call sites grows hot code. L1 instruction caches are small (typically 32 KiB), so bloat causes instruction-cache and iTLB misses, plus pressure on the decoded-uop cache. A rarely taken path inlined into a hot loop can evict the hot code itself.
- Register pressure: A bigger merged function has more live values. The allocator may spill to the stack, which can cost more than the call it removed.
- Branch prediction: Inlining can help, because each copy gets its own branch addresses and history, which is better than one shared branch with mixed behavior. It can also hurt, by increasing the number of branches competing for BTB and predictor capacity, causing aliasing.
Practical guidance: inline small hot functions, keep cold error handling out of line (noinline, [[unlikely]]), and verify by measuring with perf counters (L1i misses, IPC) rather than assuming.
Common mistakes
- Claiming
mallocof 4 GiB uses 4 GiB of RAM immediately. - Forgetting that
std::vectorinitialization touches every page. - Believing
swapoffmakes memory access fault-free. - Treating
inlineas a command to the optimizer. - Assuming more inlining is always faster.