Objective
A strategy process whose memory climbs from 2 GB at the open to 14 GB by the close will eventually be killed, usually at the worst moment. Separately, a hot path that allocates on every tick pays for it in latency. By the end of this lesson you should be able to say which tool answers which memory question and use two of them yourself.
Leaks versus growth
- A leak is memory that is no longer reachable but never freed: a raw
newwithoutdelete, a reference cycle the collector cannot break, a handle never closed. LeakSanitizer and valgrind's memcheck report these at exit with the allocation stack. - Unbounded growth is memory that is still reachable and therefore not a leak to any tool: a cache keyed by something that never repeats (order id, timestamp), an event log kept in memory, a map of "closed" orders nobody erases. It is more common in long-running trading processes and must be found by watching what grows.
- Fragmentation is when the process holds memory the allocator cannot reuse because free blocks are scattered; resident memory stays high even though live data is small.
The diagnostic question is "what is the growth rate, and which allocation site owns it?". Plot resident memory over the day: a straight line against number of events processed points to per-event retention, a step pattern points to periodic batches or container doublings.
The tools, conceptually
| Tool | How it works | Answers |
|---|---|---|
| valgrind memcheck | runs the program on a synthetic CPU, checks every access (20–50x slowdown) | leaks and invalid accesses, with stacks |
| valgrind massif | same engine, snapshots heap size over time with the allocation tree | "what owns the heap at its peak?" |
| heaptrack (Linux) | intercepts malloc/free via preloading, records every call with its stack; far faster than valgrind | peak consumers, number of allocations per site, temporary allocations, leaks |
| jemalloc / tcmalloc profiling | sampling heap profiler built into the allocator, cheap enough for production | live heap by stack, diffable between two moments |
| ASan / LeakSanitizer | compile-time instrumentation | leaks at exit and memory errors |
Python tracemalloc | hooks the Python allocator, records the traceback of each block | which source lines own the current Python heap, and how it changed between snapshots |
In an interview, the key distinction is peak and ownership (massif, heaptrack, allocator profiles) versus correctness (memcheck, ASan). For growth, take two snapshots some time apart and diff them: the site whose live bytes grew is the culprit.
Counting allocations in C++
On a latency-critical path the goal is often zero allocations after start-up. You can measure this directly by replacing the global operator new, which every new expression and standard container allocation goes through.
Worked example
counting allocations from containers and strings
Count heap allocations for: pushing 1,000 ints into a vector, the same with reserve, and storing 1,000 short versus 1,000 longer strings. Predict the counts before running.
Show solutionHide solution
#include <cstdio>
#include <cstdlib>
#include <new>
#include <string>
#include <vector>
static long g_allocs = 0;
static long g_bytes = 0;
void* operator new(std::size_t n) {
++g_allocs;
g_bytes += static_cast<long>(n);
if (void* p = std::malloc(n)) return p;
throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }
template <class F>
void count(const char* name, F&& f) {
long a0 = g_allocs, b0 = g_bytes;
f();
std::printf("%-26s %6ld allocations, %8ld bytes\n", name, g_allocs - a0, g_bytes - b0);
}
int main() {
count("push_back 1000 ints", [] {
std::vector<int> v;
for (int i = 0; i < 1000; ++i) v.push_back(i);
});
count("reserve, then push_back", [] {
std::vector<int> v;
v.reserve(1000);
for (int i = 0; i < 1000; ++i) v.push_back(i);
});
count("1000 short strings", [] {
std::vector<std::string> v;
v.reserve(1000);
for (int i = 0; i < 1000; ++i) v.emplace_back("AAPL");
});
count("1000 long strings", [] {
std::vector<std::string> v;
v.reserve(1000);
for (int i = 0; i < 1000; ++i) v.emplace_back("AAPL.NASDAQ.CONSOLIDATED");
});
}
Output with Apple clang and libc++ (-std=c++20 -O1 -g):
push_back 1000 ints 11 allocations, 8188 bytes
reserve, then push_back 1 allocations, 4000 bytes
1000 short strings 1 allocations, 24000 bytes
1000 long strings 1001 allocations, 56000 bytes
Checking the predictions.
- Growth. libc++ doubles capacity: 1, 2, 4, ..., 1024 elements, which is 11 allocations totalling bytes. Each reallocation also copies the old elements. (libstdc++ also doubles; MSVC grows by 1.5x, so counts differ by library.)
- Reserve. One allocation of exactly bytes.
- Short strings.
std::stringis 24 bytes in libc++ and stores up to 22 characters inline (the small-string optimisation), so"AAPL"needs no heap block: only the vector's bytes. - Long strings. The 24-character symbol exceeds the inline capacity, so each string allocates a 32-byte block: bytes in 1,001 allocations. On a hot path, use fixed-size symbol types or interned integer ids instead.
Worked example
finding unbounded growth with tracemalloc
A quote cache is supposed to keep the latest quote per symbol for 50 symbols, but the process grows all day. Use tracemalloc to show the growth and identify the line responsible, then compare a fixed version.
Show solutionHide solution
import tracemalloc
class QuoteCache:
"""Meant to keep the latest quote per symbol. Bug: keyed by (symbol, ts)."""
def __init__(self):
self.store = {}
def on_quote(self, symbol, ts, bid, ask):
self.store[(symbol, ts)] = (bid, ask) # a new entry every tick
class BoundedCache:
"""Fix: key by symbol only, so size is bounded by the universe."""
def __init__(self):
self.store = {}
def on_quote(self, symbol, ts, bid, ask):
self.store[symbol] = (ts, bid, ask)
for cls in (QuoteCache, BoundedCache):
tracemalloc.start()
cache = cls()
for ts in range(300_000):
cache.on_quote(f"SYM{ts % 50}", ts, 100.0 + ts * 1e-6, 100.01 + ts * 1e-6)
if (ts + 1) % 100_000 == 0:
current, peak = tracemalloc.get_traced_memory()
print(f"{cls.__name__:12s} {ts + 1:>7,} ticks: current {current / 1e3:9.1f} kB")
for stat in tracemalloc.take_snapshot().statistics("lineno")[:2]:
frame = stat.traceback[0]
print(f" line {frame.lineno:>2}: {stat.size / 1e3:9.1f} kB in {stat.count:>7,} blocks")
tracemalloc.stop()
del cache
Output (Python 3.11):
QuoteCache 100,000 ticks: current 29810.2 kB
QuoteCache 200,000 ticks: current 59633.4 kB
QuoteCache 300,000 ticks: current 84213.5 kB
line 9: 44081.0 kB in 599,915 blocks
line 23: 30539.9 kB in 899,996 blocks
BoundedCache 100,000 ticks: current 9.2 kB
BoundedCache 200,000 ticks: current 9.3 kB
BoundedCache 300,000 ticks: current 9.4 kB
line 17: 4.5 kB in 46 blocks
line 23: 2.8 kB in 53 blocks
Reading it.
- The buggy cache grows roughly linearly, about 28 kB per 100 ticks, about 280 bytes per tick: this is per-event retention, not a one-off.
- Line 9 (the dictionary insert) owns about 600,000 blocks, two per tick: the
(symbol, ts)key tuple and the(bid, ask)value tuple. Line 23 owns about 900,000 blocks, three per tick: the formatted symbol string and the two float prices, all kept alive because the dictionary references them. - None of this is a leak: every object is reachable, so a leak checker would report nothing. Only "what is growing, and where was it allocated" finds it.
- The fixed cache plateaus at about 9 kB: 50 entries, overwritten in place.
In a real process you would take a snapshot at the open and another an hour later and call snapshot2.compare_to(snapshot1, "lineno") to list the lines whose live memory grew most.
Knowledge check
A process's memory grows steadily all day, but valgrind memcheck and LeakSanitizer report no leaks at exit. What is the most likely explanation?
Knowledge check
A vector grows by doubling from capacity 1 and receives 5,000 push_backs with no reserve. How many allocations does it make?
Knowledge check
You need to know which call sites are responsible for the peak heap of a C++ service on Linux, with modest overhead. Which tool fits best?
Key takeaways
- A leak is unreachable memory; unbounded growth is reachable memory nobody prunes. Long-running trading processes suffer more from the second.
- Find growth by diffing heap snapshots over time and ranking allocation sites by the increase.
- massif and heaptrack answer "who owns the peak"; memcheck and ASan answer "is memory used correctly".
- Count allocations on hot paths by replacing
operator new; reserve containers and avoid heap strings to reach zero allocations per event. tracemallocgives the same per-line view for Python code.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).