Postfix Macro Evaluation and Lock-Free C++ Primitives
Easy · Software Engineering Fundamentals · Software Engineer · Technical Screen
Prompt
Walk through the design and C++/systems trade-offs for four connected low-latency building blocks:
- Postfix Arithmetic Interpreter with Parameterized Macros: Design a stack-based interpreter for Reverse Polish Notation (postfix) expressions supporting signed integer operations (
+,-,*,/) alongside user-defined symbolic macros (for example,CUBE n := n n * n *) that expand during evaluation. Explain which data structures provideO(1)orO(log N)macro lookup, and detail how you guard against direct or mutually recursive macro definitions. - Bounded Lock-Free SPSC Ring Buffer: Implement a fixed-capacity Single-Producer, Single-Consumer circular queue in C++11 whose capacity is a power of two. Write
enqueueanddequeuewith explicitstd::memory_orderoperations, and explain why publishing data requiresmemory_order_releaseon the writer paired withmemory_order_acquireon the reader (and symmetrically when freeing slots). - Cache-Line Isolation & False Sharing: Explain how false sharing harms tail latency when the producer and consumer run on separate CPU cores, and show how to structure your queue (using
alignasor padding) soheadandtaillive on separate cache lines. - Cross-Thread Fixed-Size Object Pool: Design a custom pool allocator to replace
malloc/freewhen one thread continuously allocates objects of typeTand another thread deallocates them, avoiding both lock contention and memory fragmentation.
Scope & Expectations
- Compare hash-based, tree-based, and interned-ID macro tables, and avoid exponential memory blowup or stack overflows by using lazy frame-stack evaluation and cycle detection.
- Show exact C++11
release/acquiresynchronization on a power-of-two ring buffer so non-atomic payload reads and writes are race-free without mutexes or atomic read-modify-write instructions. - Eliminate multi-core cache-line ping-pong with
alignas(64)separation (plus local shadow indices) and recycle cross-thread pooled objects through lock-free batch reclamation.
Step-by-step walkthrough
Part 1a: RPN evaluation and O(1) / O(log N) macro storage
Reverse Polish Notation (RPN) (also called postfix notation) places operators after their operands —
2 3 +instead of2 + 3— so expressions never need parentheses or operator-precedence rules. You scan tokens left to right with an integer stack: numbers push onto the stack, and+,-,*,/pop the right operand first, pop the left operand second, and pushleft op right(truncating/toward zero like C++, so-9 4 /gives-2).A macro definition
CUBE n := n n * n *binds a name (CUBE), an ordered parameter list (n), and a token body (n n * n *). CallingCUBEpops one value per parameter from the operand stack (in reverse parameter order, because the last argument was pushed last and sits on top!) and evaluates the body with those parameter names bound.Three ways to store macros, depending on latency requirements:
- Hash table (
std::unordered_map<std::string, Macro>in C++ /dictin Python): O(1) average-case lookup (hashing the token string takes O(token length)), with O(N) theoretical worst case under hash collisions. - Balanced binary search tree (
std::map<std::string, Macro>): Guaranteed O(log N) string comparisons in the worst case and naturally sorted macro listings. - Token interning + flat vector (best for ultra-low latency): Interning assigns each unique symbol string a sequential integer ID (
0, 1, 2, ...) once at definition/parse time, compiling macro bodies into compact bytecode structs (PUSH 5,ARG 0,MUL,CALL 3). At runtime, macro lookup ismacros[id]— worst-case O(1) array indexing with zero string hashing!
Trace both
2 3 + CUBE(CUBE n := n n * n *) and a two-parameter macro14 4 DIFF(DIFF p q := p q -) to see why reverse parameter popping matters:Trace 1: 2 3 + CUBE Trace 2: 14 4 DIFF (DIFF p q := p q -) token action stack token action stack ----- ------------------------ -------- ----- ---------------------------- -------- 2 push 2 [2] 14 push 14 [14] 3 push 3 [2, 3] 4 push 4 (top) [14, 4] + pop 3, pop 2, push 5 [5] DIFF pop q=4 first, then pop p=14 [] CUBE pop n=5, enter body [] p push bound p=14 [14] n push bound n=5 [5] q push bound q=4 [14, 4] n push bound n=5 [5, 5] - pop right=4, left=14 -> 10 [10] * pop 5, pop 5, push 25 [25] n push bound n=5 [25, 5] * pop 5, pop 25, push 125 [125]- Hash table (
Part 1b: Lazy frame-stack expansion and cycle rejection
Why naive string replacement fails. Rewriting macro names into strings before evaluation (eager textual expansion) blows up memory exponentially even without recursion! Consider
D0 := 1,D1 := D0 D0 +, ...,D40 := D39 D39 +: just 40 tiny definitions expand to more than2^40(over a trillion) tokens in RAM, and a recursive macro loops forever during expansion.Instead, expand lazily with an explicit frame stack (
frames: list[Frame]), where eachFrameholds(tokens, pos, bindings):- Memory stays O(active nesting depth) rather than O(total expanded tokens), and because we manage
frameson the heap/array instead of using C++/Python function recursion, deep macros can never crash the process with a native call-stack overflow. - Reject cycles at definition time. Because our RPN language has no
if/branch operator, any macro that can reach itself (directly likeA := A 1 +, or indirectly likeA := BandB := A 1 +) is guaranteed to loop forever! When definingNAME, perform a quick graph walk (_reaches) over referenced macros (ignoring tokens shadowed by parameter names) and reject any cycle immediately. - Enforce both
max_depthandmax_stepsbudgets.D40above has no cycle and uses only 42 stack frames, yet executes4 * 2^40 - 3steps — somax_depthcaps memory whilemax_stepscaps CPU time.
import re INTEGER = re.compile(r"-?[0-9]+") NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*") OPERATORS = {"+", "-", "*", "/"} class RpnError(Exception): pass class Frame: def __init__(self, tokens, bindings): self.tokens = tokens # tuple of body tokens (or top-level expression) self.pos = 0 # index of next token to execute in this frame self.bindings = bindings # dict mapping param_name -> int for this call def apply_operator(op, left, right): if op == "+": return left + right if op == "-": return left - right if op == "*": return left * right if right == 0: raise RpnError("division by zero") quotient = abs(left) // abs(right) # truncate toward zero to match C++ integer division return -quotient if (left < 0) != (right < 0) else quotient class RpnEvaluator: def __init__(self, max_depth=64, max_steps=1_000_000): self.macros = {} # macro_name -> (params_tuple, body_tokens_tuple) self.max_depth = max_depth self.max_steps = max_steps def define(self, line): """Parse 'NAME p1 p2 := body' and reject direct or indirect recursion cycles.""" head, sep, body = line.partition(":=") names = head.split() if not sep or not names or not all(NAME.fullmatch(n) for n in names): raise RpnError(f"invalid macro definition: {line!r}") name, params = names[0], tuple(names[1:]) if len(set(params)) != len(params): raise RpnError(f"duplicate parameter name in {line!r}") body_tokens = tuple(body.split()) if self._reaches(body_tokens, params, name): raise RpnError(f"recursive macro cycle detected for {name!r}") # Store immutable tuples so redefining a macro never mutates an in-flight Frame. self.macros[name] = (params, body_tokens) def _reaches(self, tokens, params, target): """Return True if expanding `tokens` can transitively invoke macro `target`.""" pending = [t for t in tokens if t not in params] visited = set() while pending: tok = pending.pop() if tok == target: return True if tok in visited or tok not in self.macros: continue visited.add(tok) inner_params, inner_body = self.macros[tok] for inner_tok in inner_body: if inner_tok not in inner_params: pending.append(inner_tok) return False def evaluate(self, expression): stack = [] frames = [Frame(tuple(expression.split()), {})] steps = 0 while frames: frame = frames[-1] if frame.pos == len(frame.tokens): frames.pop() continue token = frame.tokens[frame.pos] frame.pos += 1 steps += 1 if steps > self.max_steps: raise RpnError("evaluation step budget exceeded") if token in frame.bindings: stack.append(frame.bindings[token]) elif INTEGER.fullmatch(token): stack.append(int(token)) elif token in OPERATORS: if len(stack) < 2: raise RpnError(f"operator {token!r} needs two operands") right = stack.pop() left = stack.pop() stack.append(apply_operator(token, left, right)) elif token in self.macros: params, body = self.macros[token] if len(stack) < len(params): raise RpnError(f"macro {token!r} needs {len(params)} arguments") if len(frames) >= self.max_depth: raise RpnError("macro nesting depth limit exceeded") # Last parameter sits on top of the stack, so pop parameters in reverse order. bindings = {} for param in reversed(params): bindings[param] = stack.pop() frames.append(Frame(body, bindings)) else: raise RpnError(f"unknown token {token!r}") if len(stack) != 1: raise RpnError(f"expected single result on stack, got {stack}") return stack[0]- Memory stays O(active nesting depth) rather than O(total expanded tokens), and because we manage
Part 2a: Lock-free SPSC ring buffer with power-of-two masking
A Single-Producer, Single-Consumer (SPSC) queue connects exactly one writer thread to one reader thread over a fixed circular array of
Capacityslots (whereCapacityis a power of two, such as64or1024). Because only the producer modifiestail_(next write count) and only the consumer modifieshead_(next read count), neither thread ever needs a mutex or an expensive read-modify-write compare-and-swap (CAS) instruction — plain atomic loads and stores are enough!Instead of wrapping
head_andtail_back to0atCapacity, let bothstd::size_tcounters increase monotonically (0, 1, 2, ...) and mask only when indexing the array (index & (Capacity - 1)):Capacity = 8 (kMask = 7): suppose head_ = 13 (slot 13 & 7 = 5), tail_ = 21 (slot 21 & 7 = 5) Items currently in queue: tail_ - head_ = 21 - 13 = 8 == Capacity --> FULL (all 8 slots used!) If consumer reads all 8: head_ becomes 21, tail_ - head_ = 0 --> EMPTY!Keeping counters monotonic eliminates the classic "does
head == tailmean empty or full?" ambiguity without wasting a dummy slot, and because2^64is divisible by every power-of-twoCapacity, unsigned subtractiontail - headremains exact even across 64-bit wrap-around (which at 1 billion ops/sec takes 584 years).#include <atomic> #include <cstddef> template <typename T, std::size_t Capacity> class SpscQueueBasic { static_assert(Capacity >= 2 && (Capacity & (Capacity - 1)) == 0, "Capacity must be a power of 2"); static constexpr std::size_t kMask = Capacity - 1; public: bool enqueue(const T& item) { // called ONLY by producer const std::size_t tail = tail_.load(std::memory_order_relaxed); // only producer writes tail_ const std::size_t head = head_.load(std::memory_order_acquire); // sync with consumer's release if (tail - head == Capacity) return false; // queue is full buffer_[tail & kMask] = item; // Step 1: write payload to slot tail_.store(tail + 1, std::memory_order_release); // Step 2: publish new tail_ return true; } bool dequeue(T& out) { // called ONLY by consumer const std::size_t head = head_.load(std::memory_order_relaxed); // only consumer writes head_ const std::size_t tail = tail_.load(std::memory_order_acquire); // sync with producer's release if (tail == head) return false; // queue is empty out = buffer_[head & kMask]; // Step 1: read payload from slot head_.store(head + 1, std::memory_order_release); // Step 2: mark slot free return true; } private: std::atomic<std::size_t> head_{0}; std::atomic<std::size_t> tail_{0}; T buffer_[Capacity]; };Part 2b: Why release and acquire barriers are both mandatory
buffer_[slot]is a plain non-atomic variable! Without memory-ordering barriers, both the C++ compiler and weakly ordered CPUs (such as ARM64) are free to reorder memory reads and writes across different addresses as long as single-threaded logic looks unchanged.C++11's release-acquire synchronization establishes a guaranteed happens-before timeline between the two cores:
Producer Thread Consumer Thread ---------------------------------------------- ---------------------------------------------- 1. buffer_[slot] = item; (ordinary write) 2. tail_.store(t + 1, release); --- synchronizes ---> 3. tail_.load(acquire) sees (t + 1) [nothing above #2 can sink below #2] [nothing below #3 can float above #3] 4. out = buffer_[slot]; (guaranteed to see #1!)- Why producer needs
memory_order_releaseontail_.store: Prevents the compiler or CPU store buffer from publishingtail + 1beforebuffer_[slot] = itemfinishes becoming visible. Withoutrelease, the consumer can observetail + 1and read uninitialized garbage frombuffer_[slot]. - Why consumer needs
memory_order_acquireontail_.load: Prevents the compiler or CPU out-of-order load unit from speculatively readingbuffer_[slot]before readingtail_. - Why the reverse pair (
head_.store(release)->head_.load(acquire)) is equally required: Guarantees the consumer finishes copyingout = buffer_[slot]before the producer seeshead_advance on the next lap around the ring and overwrites that same slot! - Why
relaxedworks for a thread's own index, and whyseq_cstis overkill: Producer is the sole writer oftail_, so its owntail_.load(relaxed)always sees its latest value. Full sequential consistency (memory_order_seq_cst) emits an expensive full memory fence (xchg/mfenceon x86-64), whereasacquireloads andreleasestores compile to zero-overheadmovinstructions on x86-64 and lightweightldar/stlrinstructions on ARM64.
- Why producer needs
Part 3: Eliminating false sharing with cache-line alignment and index caching
CPU cores do not share individual bytes — their L1/L2 caches trade memory in fixed cache lines (
64 byteson x86-64 and most server ARM CPUs;128 byteson Apple Silicon). False sharing occurs when two independent variables modified by different cores (head_andtail_) sit inside the same 64-byte cache line:BAD (shared 64B line): [ head_ (8B) | tail_ (8B) | buffer_[0..5] ... ] Producer writes tail_ -> invalidates Consumer's L1 line -> Consumer stalls ~40-80 ns re-fetching head_! GOOD (alignas(64) per writer + local shadow index): Cache line 0 (Consumer-owned): [ head_ (8B) | cached_tail_ (8B) | 48B padding ] Cache line 1 (Producer-owned): [ tail_ (8B) | cached_head_ (8B) | 48B padding ] Cache line 2+ (Ring payload): [ buffer_[0] | buffer_[1] | ... ]Notice the second win unlocked by separating the lines: the producer stores a non-atomic shadow copy
cached_head_on its own cache line and only reads the consumer'shead_atomic whentail - cached_head_ == Capacity(the queue appears full)! Symmetrically, the consumer cachescached_tail_on its own line and only reloadstail_whenhead == cached_tail_. In steady-state traffic,enqueueanddequeueavoid cross-core index traffic on almost every call:#include <atomic> #include <cstddef> template <typename T, std::size_t Capacity> class SpscQueue { static_assert(Capacity >= 2 && (Capacity & (Capacity - 1)) == 0, "Capacity must be a power of 2"); static constexpr std::size_t kMask = Capacity - 1; static constexpr std::size_t kCacheLine = 64; // use 128 on CPUs with adjacent-line spatial prefetchers public: bool enqueue(const T& item) { // producer thread only const std::size_t tail = tail_.load(std::memory_order_relaxed); if (tail - cached_head_ == Capacity) { // shadow says full -> refresh once cached_head_ = head_.load(std::memory_order_acquire); if (tail - cached_head_ == Capacity) return false; // genuinely full } buffer_[tail & kMask] = item; tail_.store(tail + 1, std::memory_order_release); return true; } bool dequeue(T& out) { // consumer thread only const std::size_t head = head_.load(std::memory_order_relaxed); if (head == cached_tail_) { // shadow says empty -> refresh once cached_tail_ = tail_.load(std::memory_order_acquire); if (head == cached_tail_) return false; // genuinely empty } out = buffer_[head & kMask]; head_.store(head + 1, std::memory_order_release); return true; } private: // Consumer-written state isolated on its own 64-byte cache line: alignas(kCacheLine) std::atomic<std::size_t> head_{0}; std::size_t cached_tail_ = 0; // Producer-written state isolated on its own 64-byte cache line: alignas(kCacheLine) std::atomic<std::size_t> tail_{0}; std::size_t cached_head_ = 0; // Ring slots start on a fresh cache line so buffer_[0] never shares a line with tail_/cached_head_: alignas(kCacheLine) T buffer_[Capacity]; };(Note: Never place
cached_head_onhead_'s line — the producer writescached_head_, which would reintroduce false sharing onhead_!)Part 4: Lock-free cross-thread pool allocator without contention or fragmentation
When Thread A continually allocates
Tobjects and Thread B frees them, standardmalloc/freehits a worst-case asymmetric pattern: Thread B's local allocator cache fills up and has to flush batches back to a central mutex-guarded heap while Thread A's cache keeps running dry.Eliminate both locks and fragmentation with single-owner private allocation + SPSC batch reclamation:
[Thread A: Allocator Owner] [Thread B: Consumer / Releaser] +-------------------------+ 1. allocate(): pop free_[] +-----------------------------+ | slots_[N] (preallocated)| -------------------------------> | uses T*, then calls | | free_[N] (non-atomic!) | | release(obj): ~T() + | +-------------------------+ <------------------------------- | returned_.enqueue(slot) | ^ 2. reclaim() when free_ empty +-----------------------------+ +----------- drains SpscQueue<Slot*, N> in a fast batch- Zero fragmentation: Every slot is identically sized (
sizeof(T), cache-line aligned viaalignas(64)so live objects on different threads never false-share). Any free slot satisfies any allocation — external fragmentation is mathematically zero! - Zero lock contention: Thread A pops from a plain non-atomic array
free_[--free_count_]in ~2 cycles. Thread B never touchesfree_[]; it callsobject->~T()and pushes the rawSlot*ontoreturned_(SpscQueue<Slot*, N>). Because at mostNslots exist,returned_(Capacity = N, a power of two) can never overflow! Only whenfree_count_ == 0does Thread A drainreturned_back intofree_[]in one tight loop. (If multiple threads free objects allocated by Thread A, replacereturned_with a lock-free MPSC Treiber stack where releasers CAS-push and Thread A steals the whole chain atomically viahead.exchange(nullptr, acquire)— avoiding single-pop ABA bugs, where a node is popped, reused, and pushed back under the same pointer address).
#include <cstddef> #include <new> #include <utility> template <typename T, std::size_t N> class CrossThreadPool { static_assert(N >= 2 && (N & (N - 1)) == 0, "N must be a power of 2 for SpscQueue"); struct alignas(64) Slot { // 64B alignment prevents false sharing between adjacent live T objects alignas(T) unsigned char bytes[sizeof(T)]; }; public: CrossThreadPool() { for (std::size_t i = 0; i < N; ++i) { free_[i] = &slots_[i]; } free_count_ = N; } template <typename... Args> T* allocate(Args&&... args) { // Thread A (owner) only if (free_count_ == 0) reclaim(); if (free_count_ == 0) return nullptr; // pool exhausted: apply back-pressure Slot* slot = free_[free_count_ - 1]; // Construct via placement new before decrementing free_count_ so a throwing T() never leaks a slot. T* obj = new (slot->bytes) T(std::forward<Args>(args)...); --free_count_; return obj; } void release(T* object) { // Thread B (releaser) only if (object == nullptr) return; object->~T(); returned_.enqueue(reinterpret_cast<Slot*>(object)); // guaranteed true since live objects <= N } private: void reclaim() { // batch-drain freed slots back to owner Slot* slot = nullptr; while (returned_.dequeue(slot)) { free_[free_count_++] = slot; } } Slot slots_[N]; Slot* free_[N]; // Thread A private stack (zero atomics!) std::size_t free_count_ = 0; SpscQueue<Slot*, N> returned_; // lock-free return pipe from Thread B -> A };- Zero fragmentation: Every slot is identically sized (
Intuition & how it works
One unifying systems principle ties all four parts of this problem together: replace hidden runtime magic (recursive call stacks, OS locks, and malloc) with explicit pre-sized arrays where every variable has a single writer. An explicit frame stack lets an RPN macro evaluator expand nested macros without blowing the thread's call stack, and giving a producer thread and consumer thread exclusive write ownership over separate cache-aligned counters lets messages and freed memory slots cross threads with zero locks.
Naive implementations fail in predictable ways under low-latency load. Expanding RPN macros via eager string search-and-replace explodes memory exponentially (2^40 tokens across 40 tiny macro definitions); sharing an unpadded ring buffer causes false sharing (two cores fighting over the same 64-byte cache line even though they touch different variables) or silent data corruption on ARM CPUs when memory_order_relaxed reorders writes; and calling malloc on Thread A + free on Thread B triggers cross-thread heap locks and microsecond-scale OS page faults.
Trace a concrete end-to-end flow: evaluating 2 3 + CUBE (CUBE n := n n * n *) pushes 2, pushes 3, adds to [5], pops n = 5 into a lazy Frame(("n", "n", "*", "n", "*"), {"n": 5}), and computes 125 in O(depth) space. To ship 125 to a consumer thread over an 8-slot SpscQueue (kMask = 7), the producer writes buffer_[tail & 7] = 125 and publishes tail + 1 with memory_order_release; the consumer reads tail with memory_order_acquire, reads 125, and returns the slot (or returns a pooled object via CrossThreadPool::release) without taking a single lock.
Key points
- RPN macro lookup and lazy expansion. Store macros in a hash map (
unordered_map/dict) for O(1) average lookup, an ordered tree (std::map) for O(log N) worst-case lookup, or intern symbol strings into integer IDs at definition time for worst-case O(1) vector indexing. Expand macros lazily on an explicit heap/arrayFramestack (popping arguments in reverse parameter order), reject direct and indirect recursion cycles via a graph reachability walk atdefine()time, and cap bothmax_depthandmax_steps. - Monotonic power-of-two SPSC ring. Keep
head_andtail_as free-running unsignedsize_tcounters and mask only when indexing (idx & (Capacity - 1)):tail == headis empty,tail - head == Capacityis full, allCapacityslots are usable, and single-writer counters avoid compare-and-swap (CAS). - Pairwise
release/acquirebarriers. Producer writesbuffer_[slot]thentail_.store(tail + 1, release), pairing with consumer'stail_.load(acquire)before readingbuffer_[slot]. Symmetrically, consumer'shead_.store(head + 1, release)pairs with producer'shead_.load(acquire)so slots are never overwritten mid-read. Reading a thread's own index usesrelaxed. - Cache-line isolation + shadow indices. Pad
head_(plus consumer-writtencached_tail_) onto onealignas(64)cache line,tail_(plus producer-writtencached_head_) onto a secondalignas(64)line, andbuffer_onto a third — eliminating false sharing and avoiding cross-core atomic loads whenever cached indices show space/data available. - Zero-contention cross-thread object pool. Preallocate
Nalignas(64)fixed-size slots owned by Thread A's non-atomicfree_[]stack, construct via placementnew(new (bytes) T(...), initializing an object inside existing raw memory), and return freed slots from Thread B throughSpscQueue<Slot*, N>for amortized batch reclamation with zero external fragmentation.
Common mistakes
- Expanding RPN macros eagerly by repeated string substitution (exponential
2^kmemory blowup on non-recursive DAG chains likeDk := D(k-1) D(k-1) +), or popping multi-parameter macro arguments in forward order instead of reverse stack order. - Using native C++ recursion to evaluate macros, letting user input trigger an unrecoverable native stack-overflow segfault (
SIGSEGV). - Wrapping
head_andtail_moduloCapacityon store (tail = (tail + 1) & kMask), makinghead == tailambiguous between full and empty, or adding a sharedsize_counter written by both threads. - Using
memory_order_relaxed(or C++volatile, which provides zero multi-core synchronization!) ontail_/head_handoffs — a bug that appears to "work" on x86-64's strong store order yet silently corrupts messages on ARM64 or under compiler instruction scheduling. - Separating
head_andtail_withalignas(64)while accidentally placing producer-writtencached_head_onhead_'s cache line, reintroducing false sharing. - Letting Thread B push freed pointers directly onto Thread A's non-atomic free list (data race), or decrementing
free_count_before placementnewruns (leaking a slot ifT's constructor throws).
Follow-up questions
- How do you distinguish a completely full ring buffer from an empty one in your SPSC queue, and how does that compare with reserving one unused sentinel slot? If a ring buffer stores wrapped indices in
[0, Capacity - 1],head == tailrepresents both0items andCapacityitems. The sentinel-slot approach declares the queue full when((tail + 1) % Capacity) == head, which works for arbitrary (even non-power-of-two) capacities without unsigned wrap concerns, at the cost of permanently wasting 1 slot (Capacity = 1024holds only1023items — painful whensizeof(T)is large). Our free-running unsigned counter approach stores unmaskedhead_andtail_(0, 1, 2, ...):tail - head == 0is unambiguously empty andtail - head == Capacityis unambiguously full, utilizing 100% of allCapacityslots, with the sole constraint thatCapacitymust be a power of two soidx & (Capacity - 1)stays continuous across2^64unsigned integer wrap-around (avoiding a third option — a sharedatomic<size_t> count_— which forces expensive read-modify-write contention on every call). - Suppose the expression language added conditionals and permitted recursive macros — what memory-safety hazards arise, and how would you enforce a hard call-depth ceiling? Allowing recursion introduces four concrete memory hazards: (1) native call-stack overflow (
SIGSEGV) if implemented via C++ host recursion; (2) unbounded heap growth / OOM on both the macroFramestack and the integer operand stack; (3) integer overflow if precomputing expanded token counts; and (4) dangling references / use-after-free in C++ if an activeFrameholds a raw reference intostd::unordered_mapwhile a nested command redefines or deletes that macro. Mitigate all four by keeping evaluation on an explicit preallocatedstd::array<Frame, kMaxDepth>(checkingdepth < kMaxDepthbefore pushing, plus tail-call frame reuse when a recursive call is the final token of a body), capping operand stack capacity andmax_steps, and storing macro bodies behind immutable reference-counted handles (std::shared_ptr<const Body>). - Why do ultra-low-latency trading engines avoid general-purpose heap allocation (
malloc/new) on the critical path, and how would you structure startup pre-allocation instead? In low-latency trading, tail-latency variance (p99/p99.9) matters far more than average speed: whilemalloc's thread-cache fast path takes ~15–30 ns, a slow-path miss acquires arena mutexes, traverses fragmented free lists, or invokesmmap/brkand triggers ~1–5 microsecond OS minor page faults + TLB shootdowns right in the middle of an order decision. To eliminate dynamic allocation completely after startup: (1) preallocate fixed upper-bound object pools, power-of-two ring buffers, flat price-level arrays, and open-addressing hash tables during process initialization; (2) prefault every byte and lock physical RAM viamlockall(MCL_CURRENT | MCL_FUTURE)backed by2 MBhuge pages; (3) ban hidden heap allocators on the hot path (std::stringexceeding SSO capacity,std::functionheap captures,std::shared_ptrcontrol blocks,std::vector::push_backgrowth, and C++throw); and (4) override globaloperator newin integration/replay builds to abort or increment a failure counter whenever a thread-localon_hot_pathflag is active.
Follow-up questions
- How do you distinguish a completely full ring buffer from an empty one in your SPSC queue, and how does that compare with reserving one unused sentinel slot?
- Suppose the expression language added conditionals and permitted recursive macros — what memory-safety hazards arise, and how would you enforce a hard call-depth ceiling?
- Why do ultra-low-latency trading engines avoid general-purpose heap allocation (`malloc`/`new`) on the critical path, and how would you structure startup pre-allocation instead?
Similar questions
- Columnar Binary Storage Format for Market Data
- Low-Latency Tree Ensemble Inference
- Enumerate Serial Paths from a Workflow Grammar
- Internals of C++ vector, unordered_map, and Virtual Dispatch
- Maximum Group Size of Equivalent Ratios
- Filter Source Files Requiring Replication
More Jump Trading interview questions
- Fixed-Window Moving Averages in Linear Time Medium
- Low-Latency Tree Ensemble Inference Hard
- Columnar Binary Storage Format for Market Data Hard Pro
- Enumerate Serial Paths from a Workflow Grammar Easy Pro
- Internals of C++ vector, unordered_map, and Virtual Dispatch Medium Pro
- Maximum Group Size of Equivalent Ratios Easy Pro
- Filter Source Files Requiring Replication Easy Pro
- Find Non-Writable Filenames from Permission Strings Medium Pro
- Maximum Subset With Nonzero Bitwise AND Easy Pro
- Rule-Based Share Tracking and Pairwise String Reduction Medium Pro