Language-Level Memory Management (C/C++/Rust) Questions
How C and C++ expose and manage memory at the language level: pointers and pointer arithmetic, pointers to pointers and function pointers, arrays versus pointers and array decay, stack versus heap storage, manual allocation and freeing in C (malloc, realloc, free), new and delete versus malloc and free, placement new, RAII and owning smart pointers (unique_ptr, including custom deleters for C resources), shallow versus deep copies and move semantics in C++. Covers reasoning about who owns a buffer and designing ownership and lifetime contracts across function, library and plugin boundaries; dangling and uninitialized pointers, leaks, double frees, use-after-free, off-by-one errors and buffer overruns and how to prevent them; undefined behavior, strict aliasing and safe byte reinterpretation, endianness; struct layout, alignment and padding as the language defines them; and finding and diagnosing memory bugs with sanitizers, Valgrind-style tools, tracing allocators and heap-corruption triage, including allocator design and heap fragmentation at the language level. Boundary: garbage-collector behavior and tuning, embedded memory budgets, register access and packing structs to hardware layouts, OS virtual memory and paging, and lock-based concurrency are covered elsewhere.
Explain C++ move semantics and rvalue references. When does a value get moved instead of copied, what state is a moved-from object in, and what pitfalls (returning references to temporaries, misusing std::move) lead to dangling references?
Sample Answer
Direct answer
Move semantics lets a C++ object hand over its internal resources (a heap pointer, a file handle) to another object instead of duplicating them. An rvalue reference (T&&) is a reference type that binds to temporaries and to objects explicitly marked as expiring; a move constructor takes one and steals the resource, leaving the source empty. A value is moved instead of copied when the source is an rvalue (a temporary, a function's returned value, or the result of std::move(x)) and the type has a usable move operation. A moved-from object is in a valid but unspecified state: you may destroy it or assign to it, and you may only call operations that have no precondition on its value.
Terms first
- lvalue: an expression naming an object with an address you can reuse later (
a,v[0]). rvalue: a temporary or an expression whose value is about to be discarded (make(),a + b). std::move(x)does not move anything. It is exactly astatic_castto an rvalue reference (cppreference,std::move): it only says "this object may be treated as expiring". The move happens later, inside a move constructor or move assignment that acceptsT&&.- Rule of five: if a class owns a resource and defines a destructor, it needs a deliberate copy constructor, copy assignment, move constructor and move assignment (or
= deleteon some of them). The ideas below (what gets moved, what a moved-from object looks like) are the foundation; the strong exception guarantee, forwarding references and NRVO (named return value optimization) build on them.
When a move happens instead of a copy
| Situation | Result |
|---|---|
Buffer b = make(); where make returns a temporary | Mandatory elision from C++17 for a prvalue (a temporary value with no name and no address of its own, as opposed to one bound to a named variable): no copy and no move at all |
return local; of a named local | Elision (NRVO, named return value optimization: the compiler constructs the return value directly in the caller's slot, skipping the local entirely) is permitted but not guaranteed; if it does not happen, the compiler tries a move before a copy |
sink(std::move(a)), v.push_back(std::move(s)) | Move constructor chosen, source a / s is now moved-from |
Buffer c(a); with a an lvalue | Copy constructor |
std::move(k) where k is const | Binds to const T&&, which only the copy constructor accepts, so it silently copies |
std::vector growing its storage | Uses std::move_if_noexcept: moves elements only if their move constructor is noexcept (promises never to throw an exception) (or the type cannot be copied); otherwise it copies to keep its strong exception guarantee (a promise that if an operation fails partway, the container is left exactly as it was before the operation started, with nothing half-moved) (cppreference, move_if_noexcept) |
Worked example
This compiles with g++ -std=c++20 -O2 -Wall -Wextra -fsanitize=address,undefined move.cpp (GCC 14, Linux arm64, run in a container):
#include <cstdio>
#include <cstring>
#include <string>
#include <utility>
#include <vector>
#include <memory>
struct Buffer {
char* data;
std::size_t size;
explicit Buffer(std::size_t n) : data(new char[n]), size(n) { std::puts(" ctor"); }
Buffer(const Buffer& o) : data(new char[o.size]), size(o.size) {
std::memcpy(data, o.data, size); std::puts(" copy ctor (allocates + copies)");
}
Buffer(Buffer&& o) noexcept : data(o.data), size(o.size) {
o.data = nullptr; o.size = 0; std::puts(" move ctor (steals pointer)");
}
Buffer& operator=(Buffer&& o) noexcept {
if (this != &o) { delete[] data; data = o.data; size = o.size; o.data = nullptr; o.size = 0; }
std::puts(" move assign");
return *this;
}
Buffer& operator=(const Buffer&) = delete;
~Buffer() { delete[] data; }
};
Buffer make() { Buffer b(64); return b; } // NRVO or implicit move
void sink(Buffer b) { std::printf(" sink got size=%zu\n", b.size); }
int main() {
std::puts("1 prvalue -> elided/moved:"); Buffer a = make();
std::puts("2 copy from an lvalue:"); Buffer c(a); // copy
std::puts("3 std::move(lvalue):"); sink(std::move(a));
std::printf(" a.data=%p a.size=%zu after move\n", (void*)a.data, a.size);
std::puts("4 const object: std::move still copies");
const Buffer k(8);
Buffer d(std::move(k)); // const&& binds to copy ctor
std::puts("5 std::string moved-from:");
std::string s(40, 'x');
std::string t = std::move(s);
std::printf(" t.size=%zu, s.size=%zu (valid but unspecified)\n", t.size(), s.size());
s = "reuse"; // assignment is always safe
std::printf(" after assign s=%s\n", s.c_str());
std::puts("6 vector growth uses move only if noexcept:");
std::vector<Buffer> v; v.reserve(1); v.emplace_back(4);
v.emplace_back(4); // reallocates
}
Output of that run:
1 prvalue -> elided/moved:
ctor
2 copy from an lvalue:
copy ctor (allocates + copies)
3 std::move(lvalue):
move ctor (steals pointer)
sink got size=64
a.data=(nil) a.size=0 after move
4 const object: std::move still copies
ctor
copy ctor (allocates + copies)
5 std::string moved-from:
t.size=40, s.size=0 (valid but unspecified)
after assign s=reuse
6 vector growth uses move only if noexcept:
ctor
ctor
move ctor (steals pointer)
Reading it, line by line against the Buffer class: every ctor line is Buffer(std::size_t n) running, allocating new char[n] fresh. Every move ctor (steals pointer) line is Buffer(Buffer&& o) noexcept running: it copies o.data (the pointer itself, not the bytes it points to) into the new object, then sets o.data = nullptr so the old object's destructor, which runs delete[] data, deletes a null pointer (harmless) instead of the memory the new object now owns. Every copy ctor (allocates + copies) line is the expensive path: a fresh new char[o.size] followed by memcpy-ing every byte. Step 1 printed only ctor, so the compiler elided the return (NRVO): make()'s local b was never actually a separate object from a. Step 2 paid for a heap allocation and a memcpy. Step 3 copied nothing: the move constructor took the pointer and nulled the source, which is exactly the "valid state" a hand-written move must leave behind (the destructor of the source still runs, and delete[] nullptr is harmless). Step 4 shows the const trap. Step 5 shows that std::string here left s empty, but the standard only promises valid-but-unspecified, so do not depend on that; assigning to it is always safe. In step 6 the vector reallocated and relocated the old element with the noexcept move constructor.
State of a moved-from object
- Standard library types: valid but unspecified. You may destroy it, assign a new value, or call functions with no precondition (
clear(),empty(),size()); callingback()on it is undefined behaviour if it turns out empty (cppreference,std::move). - Your own types: you define it. The safe contract is "destructible and assignable"; make the move constructor leave pointers null and sizes zero, as
Bufferdoes. std::unique_ptrandstd::shared_ptr: moved-from is null (guaranteed), so dereferencing is a null dereference.
Pitfalls that produce dangling references
All six below share one theme: something died or was emptied, and a reference or pointer to it did not know.
- Returning a reference to a temporary or local. A reference does not keep its target alive. This version of the classic
longerhelper binds a reference to one of two temporaries that are destroyed at the semicolon:
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
const std::string& longer(const std::string& a, const std::string& b) {
return a.size() >= b.size() ? a : b;
}
int main(int argc, char**) {
if (argc == 1) {
// the temporaries die at the semicolon, r is left pointing at one of them
const std::string& r = longer(std::string(40, 'a'), std::string(50, 'b'));
std::printf("%c\n", r[0]);
} else {
auto p = std::make_unique<int>(7);
auto q = std::move(p); // p is now null
std::printf("%d\n", *p); // use after move
(void)q;
}
}
GCC 14 warns at compile time (-Wdangling-reference: possibly dangling reference to a temporary, with the note the temporary was destroyed at the end of the full expression), and AddressSanitizer reports at run time (g++ -std=c++20 -O1 -g -Wall -Wextra -fsanitize=address,undefined dangle.cpp, run once with no arguments). The report below is trimmed to its key lines (... marks omitted text; the process id and addresses vary from run to run):
==14==ERROR: AddressSanitizer: stack-use-after-scope on address 0xffff986000e0 ...
#2 0x401508 in main dangle.cpp:14
SUMMARY: AddressSanitizer: stack-use-after-scope ... basic_string.h:228 ...
- Using an object after moving from it. Run with any argument, the second branch of the program above moves
pintoqand then dereferencesp. UBSan (UndefinedBehaviorSanitizer, the compiler check for undefined behaviour) printsruntime error: load of null pointer of type 'int'and then, because the build also has AddressSanitizer on, the run ends with itsSEGV on unknown address 0x000000000000report (a segmentation fault: the OS killing the process for an invalid memory access). return std::move(local);Two mistakes at once. If the function returns by value, thestd::moveturns the operand into a non-name expression, which disqualifies it from NRVO (the standard's elision rule, [class.copy.elision], covers a return operand that is the plain name of a local, and GCC 14 reportsmoving a local object in a return statement prevents copy elision [-Wpessimizing-move]), so you pay for a move where plainreturn local;would have cost nothing. If the function returnsT&&orT&, it hands back a reference to a destroyed local: GCC reportsreference to local variable 'local' returned [-Wreturn-local-addr]forstd::string&& f() { std::string local(40,'q'); return std::move(local); }. Rule: return locals by value with plainreturn local;.std::moveon aconstobject, or on something you still need: silent copy, or a surprise empty source. Use it only on the last use of a value.- A move constructor not marked
noexcept: containers fall back to copying on reallocation (table above), so you lose the optimisation without any diagnostic. Mark movesnoexceptwhen they cannot throw. DeletingnoexceptfromBuffer's move constructor in the example above makes step 6 printcopy ctor (allocates + copies)instead ofmove ctor (steals pointer). - Binding a named rvalue reference and thinking it is still an rvalue. Inside a function, a parameter
T&& xis itself an lvalue (it has a name), so passing it on as an rvalue needsstd::move(x). In a template whereTis deduced,T&& xis instead a forwarding reference (it binds to lvalues and rvalues alike), and you pass it on withstd::forward<T>(x), which keeps whichever value category the caller used.
Trade-offs
Moving is the cheap path for owning types (strings, vectors, buffers, handles) and irrelevant for types with no heap resource (an int or a small struct is "moved" by copying). Prefer the rule of zero (hold std::vector / std::unique_ptr members and write no special members); hand-write the five only for a type that directly owns a raw resource.
What is strict aliasing in C and C++, and why can violating it cause bugs that appear only under optimization? What idioms do you use to inspect or reinterpret raw bytes safely?
Sample Answer
The rule. In C and C++, an object of a given type may be accessed through an lvalue (an expression naming a memory location) only of that same type or a closely related one: a qualified or signed/unsigned variant, a struct or union containing it, or a character type (char, signed char, unsigned char). cppreference's C page summarizes it: using an lvalue of a different type than the object's effective type (the type the object was created with, or last stored as) is undefined behaviour (UB), with those exceptions. Doing it anyway is called type punning: reading the bytes of an object as if it had another type. A short* and an int* are assumed not to point at the same memory, so the compiler need not reload a value after a store through the other.
Why it only bites under optimization. At -O0 every access goes to memory in order, so punning "works". With optimization on, the compiler keeps values in registers and reorders loads and stores on the strength of the no-alias assumption. Run in a gcc:14 container (GCC 14.4.0, aarch64), this program shows the effect:
#include <stdio.h>
#include <string.h>
#include <stdint.h>
static int bump_bad(int *i, short *s) { *i = 1; *s = 2; return *i; } /* UB if they alias */
static uint32_t bits_bad(float f) { return *(uint32_t *)&f; }
static uint32_t bits_good(float f) { uint32_t u; memcpy(&u, &f, sizeof u); return u; }
int main(void) {
int x = 0;
int r = bump_bad(&x, (short *)&x); /* deliberately aliasing */
printf("returned %d, x low half now %d\n", r, x);
printf("bad=%08x good=%08x\n", bits_bad(1.0f), bits_good(1.0f));
return 0;
}
gcc -O0 printed returned 2, x low half now 2. gcc -O2 -Wall printed the warning dereferencing type-punned pointer will break strict-aliasing rules for bits_bad and then returned 1, x low half now 2. The compiler's reasoning inside bump_bad goes: *i = 1 stores 1; *s = 2 writes through a short *, which cannot point at an int, so *i is still 1; therefore return *i can return the constant 1 without reading memory again. In the run the two pointers did point at the same int, so the memory held 2 and the function returned the stale 1. (The label says "low half" because the short store rewrites only the two low-order bytes of x: on a little-endian CPU, which stores the least significant byte first, those are the first two bytes in memory. The upper bytes were already 0, so x as a whole reads 2.) gcc -O2 -fno-strict-aliasing went back to returned 2. bits_bad and bits_good both printed 3f800000 in this run, so a punned read may happen to work; the rule is that you cannot rely on it, and the stale-value case above is the failure you actually see.
Safe idioms for looking at or converting raw bytes. Item 2 is the one to reach for whenever you need the bytes as a different type.
- Inspect any object as bytes: use
unsigned char *.unsigned char *p = (unsigned char *)&obj;and readp[i]. The character-type exception covers exactly this. Note it is one direction: you may read anintthroughchar *, but you may not take achararray and read it throughint *. - Reinterpret bytes as another type:
memcpyinto an object of that type.memcpy(&u, &f, sizeof u)is defined behaviour, and at-O2compilers turn small fixed-sizememcpycalls into a single register move, so it costs nothing. This is whatbits_gooddoes, and it was correct at every optimization level in the run. - C++20:
std::bit_cast<To>(from)from<bit>(cppreference: requires equal sizes and both trivially copyable types, meaning types whose bytes can be copied withmemcpysafely, such as plain integers, floats and simple structs). Same idea, and usable inconstexprcode, which is code the compiler can evaluate at compile time. - Unions: C allows reading the inactive member of a union to reinterpret bytes (cppreference notes that type punning through a union is permitted in C). I would still prefer
memcpyin shared C/C++ headers, since this is not a guarantee I would assume for C++ code. - Compiler escape hatches (
-fno-strict-aliasing(turns the assumption off for the whole build),__attribute__((may_alias))(marks one type as allowed to alias anything)) exist for code you cannot change. They make the bug harmless on that compiler but are not standard C.
Byte pointer round trip. int * to unsigned char * and back to the original int * is fine if the pointer targets a real int and is aligned. What is not fine is making an int * out of a byte buffer's address and dereferencing it: that violates both aliasing and, often, alignment.
How I catch it. Compile with -Wall -Wstrict-aliasing at -O2, and compare behaviour with -fno-strict-aliasing as a diagnostic (a bug that disappears with it is an aliasing bug). GCC's AddressSanitizer and UndefinedBehaviorSanitizer do not check aliasing, so with GCC the warning and the optimized-versus-unoptimized comparison are the tools. Clang has an experimental TypeSanitizer (-fsanitize=type) whose documentation describes it as a detector for strict type aliasing violations; it is worth a try on a Clang build, but it is still labelled experimental, so it supplements the comparison rather than replacing it.
How does an array differ from a pointer in C, particularly when passed to a function? Why does array-to-pointer decay lead to length-handling and bounds-check bugs, and what does sizeof return in each case?
Sample Answer
Direct answer. An array is a block of N contiguous elements; its name stands for the whole block, so sizeof gives N times the element size. A pointer is one variable holding an address; sizeof gives the pointer width. In most expressions an array name is converted ("decays") to a pointer to its first element, and in a function parameter int a[10] is not an array at all: it is adjusted to int *a. So inside the callee the length is gone and sizeof a is the pointer size. Bugs follow whenever code assumes the callee still knows the length.
#include <stdio.h>
#include <string.h>
static void takes_array_syntax(int a[10]) {
printf("inside callee: sizeof(a) = %zu (a is really int *)\n", sizeof a);
}
static size_t sum(const int *a, size_t n) {
size_t s = 0;
for (size_t i = 0; i < n; i++) s += (size_t)a[i];
return s;
}
int main(void) {
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int *p = arr; /* array decays to &arr[0] */
printf("in caller: sizeof(arr) = %zu, sizeof(p) = %zu\n", sizeof arr, sizeof p);
printf("element count = sizeof arr / sizeof arr[0] = %zu\n", sizeof arr / sizeof arr[0]);
takes_array_syntax(arr);
printf("p + 1 moves by %td bytes\n", (char *)(p + 1) - (char *)p);
printf("&arr has type int(*)[10]; &arr + 1 moves by %td bytes\n",
(char *)(&arr + 1) - (char *)&arr);
printf("sum = %zu\n", sum(arr, sizeof arr / sizeof arr[0]));
/* off-by-one overrun through a decayed pointer: the callee cannot know the length */
printf("reading p[10] (one past the end) is undefined behaviour\n");
fflush(stdout);
volatile int bad = p[10];
(void)bad;
return 0;
}
Built with gcc -g -O1 -fsanitize=address,undefined s4.c -o s4 (GCC also warns: 'sizeof' on array function parameter 'a' will return size of 'int *' [-Wsizeof-array-argument]) and run on a 64-bit Linux container:
in caller: sizeof(arr) = 40, sizeof(p) = 8
element count = sizeof arr / sizeof arr[0] = 10
inside callee: sizeof(a) = 8 (a is really int *)
p + 1 moves by 4 bytes
&arr has type int(*)[10]; &arr + 1 moves by 40 bytes
sum = 55
reading p[10] (one past the end) is undefined behaviour
then AddressSanitizer stops the program with ERROR: AddressSanitizer: stack-buffer-overflow ... READ of size 4, and its report says the access is at offset 88 of a frame object arr that spans [48, 88): that 88 is the array's own starting offset (48, where ASan placed it in the stack frame, which is bookkeeping, not something you compute) plus its full 40-byte size (10 ints x 4 bytes = 40), so 48 + 40 = 88 is exactly one int past the array's last byte, the first byte p[10] touches.
What differs
array int arr[10] | pointer int *p | |
|---|---|---|
sizeof | 40 (10 x 4 bytes) | 8 on a 64-bit target |
| Storage | the elements themselves | one address |
| Can be reassigned | no | yes |
& yields | int (*)[10], a pointer to the whole array | int ** |
| Passed to a function | decays to &arr[0] | copied as is |
Decay and length bugs
Once decayed (the array name is replaced by a plain pointer to its first element), only the address travels. The callee cannot compute the length, so:
sizeof a / sizeof a[0]inside the callee gives 8/4 = 2 forint *, not 10. This is the classic bug; the compiler warning above flags it.- Callers must pass the length (
size_t n) alongside the pointer, and the callee must check indexes against it. Nothing in C checks bounds for you:p[10]is UB, and usually just reads or overwrites the neighbouring object, which is how overruns become security bugs. - Use
sizeof arr / sizeof arr[0]only in the scope wherearris a real array. Do not apply it to a function parameter, a pointer frommalloc, or a string literal's decayed address.
Pointer arithmetic basics
p + 1 advances by sizeof(*p) bytes, not by 1. The run shows 4 bytes for int * and, for &arr + 1, 40 bytes because the pointed-to type is the whole array. a[i] is defined as *(a + i). Pointer arithmetic is defined only within an array object or one element past its end (you may form that one-past address, but not dereference it).
Where this bites in network frame parsing
When a receive buffer is cast to a header struct or walked with p += n, the length that arrived on the wire is attacker-controlled. Treat (pointer, length) as a pair, check remaining >= needed before every field read, and never trust a length field inside the frame to stay within the buffer without comparing it to the bytes actually received. Subtracting or adding to lengths in unsigned types also wraps silently, so check before subtracting.
Pitfall
Passing arr and writing int a[10] in the signature is misleading documentation: the 10 is ignored. Prefer const int *a, size_t n.
In C or C++, what is the difference between stack and heap memory, what does each mean for an object's lifetime, and when does the distinction cause bugs such as stack overflow or leaks?
Sample Answer
Direct answer. The stack holds automatic (local) variables. The compiler reserves space in a function's stack frame (the block of stack memory that holds that one call's local variables and bookkeeping) when it is called, and it is released automatically when the function returns, so lifetime equals the enclosing scope. The heap holds objects the program explicitly allocates (malloc in C, new in C++); they live until the program frees them, regardless of scope, which makes the programmer responsible for the lifetime. Stack bugs are overflow (too deep or too large) and returning addresses of locals. Heap bugs are leaks, double frees and use after free.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int *make_on_heap(void) {
int *p = malloc(sizeof *p); /* lives until free(), whatever the scope */
*p = 5;
return p;
}
static long depth(long n) {
volatile char pad[4096]; /* 4 KiB frame per call */
pad[0] = (char)n;
if (n == 0) return pad[0];
return depth(n - 1) + pad[0];
}
int main(int argc, char **argv) {
int local = 1;
int *h = make_on_heap();
printf("stack addr %p, heap addr %p\n", (void *)&local, (void *)h);
printf("heap value after the function returned: %d\n", *h);
free(h);
if (argc > 1) {
long n = strtol(argv[1], NULL, 10);
printf("recursing %ld levels, ~%ld KiB of stack\n", n, n * 4);
depth(n);
printf("returned normally\n");
}
return 0;
}
Built with gcc -O0 -g stack_overflow_demo.c -o stack_overflow_demo and run in a Linux container (ulimit -s printed 8192, meaning an 8 MiB limit on the main thread's stack):
$ ./stack_overflow_demo 1000
stack addr 0xffffd3d6dafc, heap addr 0x219072a0
heap value after the function returned: 5
recursing 1000 levels, ~4000 KiB of stack
returned normally
$ ./stack_overflow_demo 100000 # 100000 frames of about 4 KiB: roughly 390 MiB requested
Segmentation fault
$ echo $?
139
Reading the code: volatile tells the compiler that every read and write of pad is an observable side effect that it may not remove (cppreference: such an access "cannot be optimized out"). Without it the compiler could see that pad is barely used and shrink or delete the array, and the frames would no longer be big. The 4096 is chosen so that each call really uses about 4 KiB (4096 bytes), which makes the limit easy to hit: 8 MiB is 8192 KiB, and 8192 / 4 = 2048 is only an upper bound on the number of frames. Each frame is a little more than 4096 bytes (the array plus the saved registers and return address), and main, the environment and the loader also use some stack, so the real limit is slightly lower: in this container (aarch64, GCC 14, -O0) 2030 levels returned normally and 2035 crashed. That is why 1000 levels pass and 100000 do not.
Here is the stack while depth(3) is at its deepest call, drawn with the top of the stack at the bottom (illustrative, not to scale; on common platforms the stack grows toward lower addresses):
main frame: argc, argv, local, h
depth(3) frame: n = 3, pad[4096]
depth(2) frame: n = 2, pad[4096]
depth(1) frame: n = 1, pad[4096]
depth(0) frame: n = 0, pad[4096] <- stack pointer (the register marking the current top of the stack)
Each return removes the bottom frame and moves the stack pointer back up; no call to a memory manager is involved.
(Addresses change per run. The status 139 is the shell's 128 plus signal 11, SIGSEGV.) The heap value survived the return of make_on_heap, which a local variable would not. 1000 frames of about 4 KiB fit in 8 MiB; 100000 do not.
Lifetime and cost
| Stack | Heap | |
|---|---|---|
| Who frees | automatic at scope end | the program (free / delete), or an owner object |
| Size known at | compile time (usually) | run time |
| Limit | small fixed limit per thread | much larger, limited by memory |
| Cost to allocate | moving the stack pointer | a call into the allocator (the C library code behind malloc that keeps track of which heap blocks are free), which searches for a free block |
| Failure mode | stack overflow crash | malloc returns NULL; leaks grow slowly |
Where the distinction causes bugs
- Returning the address of a local (
return &x;) leaves a dangling pointer, because the frame is gone. - Stack overflow from deep or unbounded recursion, or from large locals such as
char buf[1 << 20]. It shows up as a segmentation fault with no helpful message, as above; in a debugger the backtrace (the list of function calls that are active at the moment, innermost first) is thousands of identical frames. Fixes: iterate instead of recurse, bound the depth, move large buffers to the heap orstaticstorage, or raise the limit (ulimit -sfor the process, or the thread's stack size at thread creation). - Leaks: heap memory with no remaining pointer to it, so it is never freed (a long-running service grows until the OS kills it).
- Stack size depends on the platform and the thread. Do not assume 8 MiB: new threads often get a different default, and embedded targets may have a few KiB.
Code review checklist
- Does any function return, store in a global, or hand to another thread the address of a local?
- Is any recursion bounded by input an attacker or a user controls?
- Are large local arrays or variable-length arrays sized from input?
- For each
malloc/new, which line frees it on every path, including early returns and error paths? - Is ownership of every heap pointer stated (who frees)?
Pitfalls
In C++, prefer automatic objects and standard containers: std::vector keeps its elements on the heap but the vector object itself is automatic, so it frees them when it goes out of scope. That removes most manual new/delete pairs. Neither region is "fast" or "slow" in the abstract: the stack's advantage is that allocation and release are nearly free, and the same few stack addresses are reused by call after call, so they tend to already sit in the processor's small, fast cache memory. It is not that the stack is bigger.
You are designing a general-purpose memory allocator for a multithreaded C or C++ program. How would you use per-thread caches, size classes, and a shared free list, and how do you keep fragmentation and contention low while handling frees that arrive on a different thread than the allocating one?
Sample Answer
Direct answer. Split allocation into size classes (buckets like 32/64/128/256 bytes; every request is rounded up to the bucket above it), give each thread its own cache per class for the lock-free fast path, and fall back to a shared central structure only when a thread's cache is empty (refill) or overfull (flush), moving a batch of blocks per lock acquisition instead of one. Frees always go to the freeing thread's own cache, so a block allocated on one thread and freed on another never needs the original owner; the thread-exit path flushes whatever is left in a dying thread's cache back to the shared structure so nothing is stranded.
Size classes. Round every request up to the nearest class (32, 64, 128, 256 bytes, etc., typically power-of-two or a fixed small ratio apart). This bounds internal fragmentation (space wasted inside an allocated block because it is bigger than what was requested) to the gap between the request and its class (worst case just under 2x for adjacent power-of-two classes, for any request above the smallest class; a 1-byte request in a 32-byte class wastes 31 of its 32 bytes, so the smallest class is where waste per request is highest) while making every free list within a class hold uniformly-sized blocks, so there is no free-list search and no external fragmentation (free space scattered between live blocks, too small or too split up to satisfy a new request) within a class. Requests larger than the biggest class fall back to the system allocator directly; this pool only targets small, frequent objects.
Per-thread cache (fast path). Each thread keeps a private singly-linked free list per size class, stored in thread-local storage (TLS: a separate copy of the variable for every thread, so each thread reads and writes its own without needing a lock), touched with zero locks and zero atomics: allocate pops the head, free (on whichever thread calls it) pushes to the head of that thread's own list for that class. This is the entire point of the design: the overwhelmingly common case touches no shared state at all, so there is no contention (two or more threads trying to use the same lock or shared data at once, which stalls one of them) on the hot path.
Shared central list and batching (slow path). When a thread's cache for a class is empty, it takes one lock on the central structure for that class and pulls a whole batch (for example 32 blocks) in one critical section (the span of code that holds the lock), not one block at a time; when a thread's cache overflows a cap, it pushes a batch back the same way. Batching is what keeps contention low under many threads: the number of lock acquisitions is divided by the batch size, not by the allocation count. The central structure itself gets new memory from the OS in large slabs (a big contiguous chunk of memory, carved up bump-allocated: sequentially handing out the next free address and advancing a pointer, with no free-list bookkeeping needed until the slab itself needs reclaiming) only when both its free list and the current slab are exhausted, so slab acquisition from the OS is rare relative to the allocation rate.
Cross-thread frees. Because every free goes to the freeing thread's cache regardless of which thread originally allocated the block, there is no per-block owner field and no cross-thread signaling needed for the common case. The cost shows up only in aggregate: if one thread (a producer) allocates heavily and another (a consumer) frees everything, the consumer's cache fills past its cap repeatedly and flushes to the central list, while the producer's cache empties repeatedly and refills from the central list; that traffic is bounded by the batch size, not the per-allocation rate, which is exactly what keeps contention from scaling with throughput.
Alternative: send each free back to the block's owner. The design above lets blocks migrate: a block is cached by whichever thread freed it, and returns to the allocating thread only after a flush goes through the central list and a later refill. The main alternative gives every slab (a run of same-size blocks) an owner thread; a free from any other thread pushes the block onto that slab's separate remote-free list with a single atomic compare-and-swap, and the owner drains that list into its private list the next time it needs blocks. mimalloc is built this way (its documentation describes one list per page for the owner's own frees and another for frees from other threads). The trade-off: owner-return keeps blocks next to the slab they came from and needs no central lock for a cross-thread free, but it needs a per-slab owner field, a way to find the slab from a bare pointer (aligned slabs or a page map), an atomic operation on every cross-thread free, and a plan for slabs whose owner has exited or gone idle. The cache-and-batch design above pays a lock only once per batch and tracks no ownership, but it lets memory wander between threads, which can hand two threads blocks that share a cache line (false sharing: two cores writing different variables in the same typically 64-byte line, so the line bounces between them).
Thread-exit reclamation. A thread's cache lives in thread-local storage and has to be flushed when the thread dies: in C++ a thread_local object whose destructor does the flush, in C a destructor registered with pthread_key_create that runs at thread exit. Either one returns every remaining block (in batches) to the shared central structure for each class, so a short-lived thread's leftover cached blocks are not lost to other threads.
Worked example. A minimal version of this design: a thread-local cache with a batch size of 32 and a cap of 64, one mutex-protected central free list that bump-allocates 64 KiB slabs, and a producer thread that allocates 102,400 blocks of 64 bytes and hands them over a 256-slot bounded queue to a consumer thread that frees every one (so every free crosses threads). The consumer also checks each block's marker and index to catch corruption or duplication:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BLK 64
#define BATCH 32
#define CAP 64
#define SLAB (64*1024)
#define N 102400
typedef struct node { struct node *next; } node;
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static node *central; static char *slab; static size_t used = SLAB; static long locks, slabs;
typedef struct { node *head; int n; } cache;
static __thread cache tc;
static void refill(void){
pthread_mutex_lock(&mu); locks++;
for(int i=0;i<BATCH;i++){
node *b=central;
if(b) central=b->next;
else { if(used+BLK>SLAB){ slab=malloc(SLAB); slabs++; used=0; } b=(node*)(slab+used); used+=BLK; }
b->next=tc.head; tc.head=b; tc.n++;
}
pthread_mutex_unlock(&mu);
}
static void flush(void){
pthread_mutex_lock(&mu); locks++;
for(int i=0;i<BATCH;i++){ node *b=tc.head; tc.head=b->next; tc.n--; b->next=central; central=b; }
pthread_mutex_unlock(&mu);
}
static void *palloc(void){ if(!tc.head) refill(); node *b=tc.head; tc.head=b->next; tc.n--; return b; }
static void pfree(void *p){ node *b=p; b->next=tc.head; tc.head=b; tc.n++; if(tc.n>=CAP) flush(); }
/* bounded queue */
#define Q 256
static void *q[Q]; static int qh,qt,qc; static pthread_mutex_t qm=PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t nf=PTHREAD_COND_INITIALIZER, ne=PTHREAD_COND_INITIALIZER;
static void *producer(void *a){ (void)a; for(int i=0;i<N;i++){ unsigned *p=palloc(); p[2]=0xC0FFEE; p[3]=i;
pthread_mutex_lock(&qm); while(qc==Q) pthread_cond_wait(&nf,&qm); q[qt]=p; qt=(qt+1)%Q; qc++; pthread_cond_signal(&ne); pthread_mutex_unlock(&qm);} return 0; }
static long bad; static char *seen;
static void *consumer(void *a){ (void)a; for(int i=0;i<N;i++){ pthread_mutex_lock(&qm); while(!qc) pthread_cond_wait(&ne,&qm); unsigned *p=q[qh]; qh=(qh+1)%Q; qc--; pthread_cond_signal(&nf); pthread_mutex_unlock(&qm);
if(p[2]!=0xC0FFEE||p[3]>=N||seen[p[3]]) bad++; else seen[p[3]]=1; pfree(p);} return 0; }
int main(void){ seen=calloc(N,1); pthread_t a,b; pthread_create(&a,0,producer,0); pthread_create(&b,0,consumer,0); pthread_join(a,0); pthread_join(b,0);
printf("blocks freed on the other thread: %d, corrupted or duplicated: %ld\ncentral lock acquisitions: %ld for %d allocs + %d frees\nslabs of 64 KiB obtained: %ld (no reuse would be %d)\n",N,bad,locks,N,N,slabs,N*BLK/SLAB); return 0; }
Compiled with gcc -O2 -Wall -Wextra -pthread (GCC 14, Linux arm64, in a container) and run five times, it printed the same thing every time:
blocks freed on the other thread: 102400, corrupted or duplicated: 0
central lock acquisitions: 6399 for 102400 allocs + 102400 frees
slabs of 64 KiB obtained: 1 (no reuse would be 100)
The same file also ran with no report under -fsanitize=thread and under -fsanitize=address,undefined. Where 6399 comes from: the producer's cache is empty once per 32 allocations, so 102,400 / 32 = 3,200 refills; the consumer's cache flushes 32 blocks whenever it reaches the cap of 64, which first happens on its 64th free and then once per further 32 frees, so (102,400 - 64) / 32 + 1 = 3,199 flushes (the last blocks stay in its cache below the cap). 3,200 + 3,199 = 6,399 lock acquisitions, one per batch rather than one per operation (204,800 operations, so about 32 operations per lock acquisition). Where the slab count comes from: a 64 KiB slab is 65,536 bytes, so it holds 65,536 / 64 = 1,024 blocks. Without reuse, 102,400 blocks would need 102,400 / 1,024 = 100 slabs (6,553,600 bytes, about 6.25 MiB). With recycling only a handful of blocks are ever outstanding at once: at most 256 in the queue, one in each thread's hand, fewer than 32 in the producer's cache and fewer than 64 in the consumer's, about 350 in total, so the central free list always has something to give back before a new block must be carved and one slab (1,024 blocks) is enough. A larger queue or cache cap raises that peak and the slab count with it.
What this prototype leaves out. It implements one size class (64 bytes) and has no thread-exit flush, so the consumer thread ends holding 32 cached blocks that are never returned to the central list (the producer ends with none, because 102,400 is a multiple of the batch size); the size-class table and the exit-time flush described above are the design, not code the program exercises. Blocks freed on a thread other than the allocator stay in the freeing thread's cache or go to the central list, so slabs are never handed back to the OS here; a real allocator tracks per-slab live counts (or per-slab owners) so a fully free slab can be returned or reused for another size class. Memory carved for one size class also cannot serve another class, which is the main way segregated size classes strand memory between classes.
Hardening for a long-running, security-sensitive process. These add real protection and are extensions layered on top of the per-thread-cache design: guard regions (an unmapped or poisoned page around slabs, or redzone bytes, a sentinel buffer, between blocks) that turn a small overflow into an immediate fault instead of silent corruption; corruption telemetry (a checksum or canary value written into each block's header and checked on free, so a corrupted block is detected and logged rather than silently reused); and zeroing sensitive buffers on free so secret data is not readable in the next object that reuses the same bytes, which costs one memset-sized write per free but closes a real information-disclosure path (freed-but-not-zeroed memory handed to the next consumer, same reuse mechanism that makes allocators fast).
Fragmentation and lifetime-based pooling for mixed workloads. When objects span wildly different lifetimes (some live for one request, some for the whole process), one global allocator still fragments over time because short-lived and long-lived objects interleave in the same slabs. The mitigation is arenas by lifetime: a request-scoped arena (a block of memory handed out in pieces for one logical duration) that is bulk-freed (reset to empty, not walked object by object) at the end of each request, separate from a long-lived arena for objects that outlive requests. This trades per-object free cost (a single arena reset instead of N individual frees) for the restriction that nothing in a request arena can outlive the request.
Trade-offs and pitfalls. The batch size is the key tuning knob: too small and you are back to per-operation lock contention; too large and a thread exiting early strands a large batch that must all be walked and flushed at once. Sized free (the caller must pass the correct size class, as a multi-class version of this design does; the single-class prototype above has no size argument) avoids a per-block header but means a size mismatch between alloc and free is a silent corruption bug with no detection; a production allocator typically adds a debug-mode header check for exactly this reason. Do not conflate this allocator's per-class caches with a general-purpose malloc replacement: size classes above the largest bucket fall straight through to the system allocator, so this design only wins for the common case of many small, similarly-sized objects, which is the case stated in the question.
Unlock Full Question Bank
Get access to all 14 Language-Level Memory Management (C/C++/Rust) interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.