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.
In C, when would you store or pass a function pointer or callback, and what checks and conventions make invoking it safe? Think of event handlers, parsers, or plugin hooks.
Sample Answer
Direct answer
Store or pass a function pointer when behavior must be chosen at runtime without the caller knowing the implementation: event handlers, a table of commands, a parser's per-token action, a plugin or driver hook, a comparison function for qsort. Safe use rests on a few conventions: one typedef that fixes the signature, a void *user_data argument so the callback needs no globals, a NULL check immediately before the call, a table of pointers that is const, and a written rule for who owns the user data and for how long it stays valid.
Conventions and checks that make invocation safe
- One typedef is the contract. Calling a function through a pointer of a different function type is undefined behavior, so a single
typedef int (*handler_fn)(void *ctx, const char *arg);used for both storage and definitions lets the compiler check every assignment. - Check for NULL right before the call, and decide what NULL means: "no handler registered" is a legitimate state in many designs (a not-yet-implemented command, an optional hook). Reject a NULL callback at registration time if it is never valid, so the failure is near the cause.
- Pass context explicitly. A
void *ctxparameter that the registrant supplies and gets back unchanged avoids global state. The callee casts it to the type the registrant promised; nothing checks that, so document it and keep the type next to the function. - Make dispatch tables
constso they sit in read-only data and a stray write cannot redirect a handler. Validate any index taken from input before using it:if (idx >= N) return ERR;. - State lifetime and threading rules. How long must
ctxstay valid after registration? Can the callback be invoked after unregister? Can it re-enter the API? A registered callback that outlives its context is a use-after-free, so the lifetime rule belongs in the contract. - Define the error contract. What the callback returns, whether it may block, and whether it may call back into the caller's API.
- Do not cast function pointers to other types or to
void *to make things fit; wrap with a function of the correct signature instead.
Worked example: a command dispatcher
#include <stdio.h>
#include <string.h>
/* One typedef is the contract: every handler has exactly this signature. */
typedef int (*handler_fn)(void *ctx, const char *arg);
struct command {
const char *name;
handler_fn fn; /* NULL means "recognised but not implemented in this build" */
};
struct counter { int hits; };
static int cmd_ping(void *ctx, const char *arg)
{
struct counter *c = ctx; /* void * back to the type the registrant promised */
c->hits++;
printf("pong %s (hits=%d)\n", arg ? arg : "", c->hits);
return 0;
}
static int cmd_reset(void *ctx, const char *arg)
{
(void)arg;
((struct counter *)ctx)->hits = 0;
return 0;
}
/* const table: lives in read-only data, so a stray write cannot redirect a handler. */
static const struct command table[] = {
{ "ping", cmd_ping },
{ "reset", cmd_reset },
{ "trace", NULL },
};
/* -1 unknown command, -2 known but unimplemented, otherwise the handler's own result. */
int dispatch(const char *name, void *ctx, const char *arg)
{
if (name == NULL) return -1;
for (size_t i = 0; i < sizeof table / sizeof table[0]; i++) {
if (strcmp(table[i].name, name) == 0) {
handler_fn fn = table[i].fn;
if (fn == NULL) return -2; /* check immediately before the call */
return fn(ctx, arg);
}
}
return -1;
}
int main(void)
{
struct counter c = { 0 };
printf("rc=%d\n", dispatch("ping", &c, "a"));
printf("rc=%d\n", dispatch("ping", &c, "b"));
printf("rc=%d\n", dispatch("trace", &c, ""));
printf("rc=%d\n", dispatch("nope", &c, ""));
printf("rc=%d hits=%d\n", dispatch("reset", &c, ""), c.hits);
return 0;
}
Compiled with gcc -O2 -Wall -Wextra -fsanitize=address,undefined fp.c and run (GCC 14.4.0, Linux arm64):
pong a (hits=1)
rc=0
pong b (hits=2)
rc=0
rc=-2
rc=-1
rc=0 hits=0
ping runs twice and the shared struct counter records both hits through ctx. trace is in the table with a NULL pointer, so dispatch returns -2 without calling anything. An unknown name returns -1. reset zeroes the counter through the same ctx mechanism.
Where function pointers appear
- Event handlers and callbacks (GUI, network, timers): pointer plus
user_data. - Parsers: a table indexed by token or opcode, one action per entry.
- Plugin hooks and driver structs: a struct of function pointers (a vtable by hand) filled at load time.
- Embedded interrupt and state-machine tables: a
constarray of handlers in flash.
Trade-offs and pitfalls
- Indirect calls usually prevent inlining (unless the compiler can see the target) and hamper some static analysis, and an indirect call through attacker-writable memory is a classic control-flow hijack target, hence
consttables and bounds checks. - A callback invoked after its
ctxis freed is the dominant real-world failure; the answer is an ownership rule, not a NULL check. - Do not pretend a NULL check proves the pointer is valid: it excludes only NULL, not dangling or garbage values.
What is undefined behavior in C and C++, and why is it especially dangerous in code that handles untrusted input? Give examples that look harmless in review but can become exploitable or non-deterministic at runtime.
Sample Answer
Direct answer
Undefined behavior (UB) means the language standard places no requirements on what the program does once an execution hits certain constructs. The program may crash, may appear to work, or may do something that changes from one compiler version or flag to the next. It is especially dangerous with untrusted input because the attacker chooses the values, and the compiler is allowed to optimize on the assumption that UB never happens, so the checks you wrote can disappear and the memory errors that remain can be steered.
What UB is, precisely
The standard does not say "this crashes". It says there are no restrictions on behavior, and compilers are not required to diagnose it (cppreference, "Undefined behavior": https://en.cppreference.com/w/c/language/behavior). Two consequences matter in practice:
- The compiler reasons backwards from the assumption that UB cannot occur. If a branch can only be reached by overflowing a signed integer, the compiler may treat that branch as dead and delete it.
- Behavior is not stable. A bug that "works" at one optimization level, on one compiler version, or with one stack layout can break after an unrelated change.
Common UB, why it looks harmless in review, and a mitigation for each
| UB | Why a reviewer passes it | What goes wrong with attacker input | Mitigation |
|---|---|---|---|
| Out-of-bounds read or write (including off-by-one) | The loop "obviously" stops at the end | Write past the end overwrites neighbouring data, a saved return address (the stack slot a function jumps back to when it returns, so overwriting it redirects execution) or a function pointer (a variable holding the address of code to call); a read past the end leaks memory | Carry the length with the pointer, check len against the size before every copy, build tests with AddressSanitizer |
| Use-after-free | The pointer is still in scope and compiles fine | The freed block is reallocated to attacker-influenced data, so the stale pointer now reads or writes someone else's object | Set the pointer to NULL after free, give every block one clear owner, test with AddressSanitizer |
| Double free | Two cleanup paths each look correct | Corrupts the allocator's bookkeeping, which can become a write primitive (a flaw that lets an attacker write chosen bytes to chosen addresses) | One owner frees; NULL after free; AddressSanitizer reports it |
| Signed integer overflow | a + b on int looks like plain arithmetic | A size computed as count * width wraps, a small buffer is allocated, and a later copy overruns it. The compiler may also delete a check written as x + 1 > x | Use size_t for sizes; test before the operation (a > INT_MAX - b) or use __builtin_add_overflow (GCC and Clang) |
| Strict-aliasing violation | A cast from char * to uint32_t * "just reinterprets bytes" | Reading an object through an incompatible type is UB, so the optimizer may reorder or drop the load and use stale data | Copy with memcpy into a correctly typed object; access through char types, which the rule exempts (https://en.cppreference.com/w/c/language/object) |
| Null dereference before the null check | The check is right there, just one line late | The compiler assumes the pointer is non-null after the dereference and removes the check | Check first, dereference second |
| Reading an uninitialized variable | It "is always zero in testing" | Contents come from whatever the stack held earlier, which can be attacker influenced | -Wall -Wextra warnings, and initialize at declaration |
Strict aliasing in one example: the table's char * to uint32_t * cast reads bytes through the wrong type. The defined way is to copy the bytes into an object of the right type. Built as a complete program with gcc -Wall -Wextra (no warnings) in an arm64 Linux container (GCC 14.4.0; little-endian, so the first byte is the least significant), it prints v = 1:
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int main(void) {
unsigned char bytes[4] = { 1, 0, 0, 0 };
uint32_t v;
memcpy(&v, bytes, sizeof v); /* defined: copy the bytes into a real uint32_t */
printf("v = %u\n", v); /* prints: v = 1 */
return 0;
}
Unsigned arithmetic is the contrast case: it is defined to wrap modulo 2^n, so UINT_MAX + 1 is 0, not UB. Signed overflow is UB and may wrap, trap, or be optimized out (https://en.cppreference.com/w/c/language/operator_arithmetic). That asymmetry is why size and offset math belongs in size_t.
Worked example 1: a guard the compiler removes
#include <limits.h>
#include <stdio.h>
/* Looks like an overflow guard. Signed overflow is UB, so the compiler may fold it (replace it by the constant) to 1. */
int will_not_wrap(int x) { return x + 1 > x; }
int main(void) {
printf("INT_MAX + 1 > INT_MAX -> %d\n", will_not_wrap(INT_MAX));
return 0;
}
Compiled and run in a Linux arm64 container with GCC 14.4.0:
gcc -O0 ub.c -> INT_MAX + 1 > INT_MAX -> 1
gcc -O2 ub.c -> INT_MAX + 1 > INT_MAX -> 1
gcc -O2 -fwrapv ub.c -> INT_MAX + 1 > INT_MAX -> 0
At -O2 the whole function compiled to mov w0, 1; ret. On arm64, w0 is the 32-bit register that carries a function's return value (the Arm AAPCS64 calling standard uses r0 to r7 for arguments and results), so this reads "put 1 in the return register, then return": it never even looks at x, and it returns true for every input, so the "overflow guard" guards nothing. With -fwrapv (tell GCC signed overflow wraps) the result is the 2's-complement answer, 0. (2's-complement is the usual way machines store signed integers: adding 1 to the largest value gives the most negative one, so INT_MAX + 1 > INT_MAX is false.) The point is not that wrapping is "right", it is that the program's meaning depended on a compiler assumption nobody wrote down. Notice also that on this GCC the check was folded away even at -O0: do not assume "debug builds are safe".
Worked example 2: a null check deleted
#include <stdio.h>
struct pkt { int len; };
/* Dereference first, check later: the check can be deleted. */
int get_len(struct pkt *p) {
int n = p->len;
if (p == NULL) return -1;
return n;
}
int main(void) {
struct pkt a = { 42 };
printf("%d\n", get_len(&a));
return 0;
}
Built with gcc -O2 -S for arm64, get_len came out as just ldr w0, [x0] then ret. x0 holds the first argument, which is p, so ldr w0, [x0] means "load the 4 bytes at the address in p into the return register", that is p->len, and ret returns it. The p == NULL test is gone, because after p->len the compiler may assume p is not null. In a real parser the same shape appears when a length field is read from a header before the header pointer is validated.
Worked example 3: catching it at runtime
#include <limits.h>
#include <stdio.h>
int main(int argc, char **argv) {
(void)argv;
int x = INT_MAX - 1 + argc; /* argc is 1 when run with no arguments: INT_MAX */
int y = x + argc; /* INT_MAX + 1: signed overflow, undefined */
printf("y = %d\n", y);
return 0;
}
gcc -O1 -fsanitize=undefined ub3.c && ./ub3 prints ub3.c:7:9: runtime error: signed integer overflow: 1 + 2147483647 cannot be represented in type 'int' and then y = -2147483648. With -fno-sanitize-recover=undefined it stops with exit status 1 instead of continuing. -fsanitize=undefined instruments various computations to detect UB at runtime, and -fsanitize=signed-integer-overflow is the specific overflow check (GCC manual, Instrumentation Options: https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html).
Detection and prevention toolbox
- Compile-time:
-Wall -Wextra(and the compiler's static analyzer, or clang-tidy / Coverity-class tools). They catch only some patterns, so a clean compile is not evidence that the code is free of UB. - Test-time: build unit tests and fuzz targets (fuzzing feeds the code huge numbers of generated inputs; a fuzz target is the small function that receives each one) with
-fsanitize=address,undefined. AddressSanitizer finds out-of-bounds and use-after-free; UBSan finds overflow, bad shifts, misaligned access. Fuzzing with attacker-shaped input is what makes the sanitizers find input-dependent bugs. - Production hardening (reduces impact, does not remove the bug). Treat the layers above as first priority and these as the last line:
-fstack-protector-strong: GCC places a guard value (a canary) next to the return address in functions with local arrays or addresses of locals, and checks it before returning; a stack overflow that overwrites it aborts the program.-D_FORTIFY_SOURCE=2: with optimization on, glibc adds lightweight checks to string and memory functions such asmemcpyandstrcpyto detect some buffer overflows (per the glibc feature-test-macros man page).- A non-executable stack: the memory holding locals cannot be run as code, so injected bytes cannot simply be executed.
- Address randomization (ASLR): the kernel places the stack, heap and libraries at unpredictable addresses (
randomize_va_spacein the Linux kernel documentation), so an attacker cannot hard-code them. These turn many overflows into a crash, which is a denial of service rather than code execution, but the underlying UB is still there.
- Language choice: for new parsers of untrusted data, a memory-safe language removes whole classes of the table above.
Constrained environments (embedded, no OS)
Sanitizers need runtime support and memory, which a small device usually lacks. The usual pattern is: keep protocol parsing and buffer logic in plain portable C, compile it on a host with the sanitizers and a fuzzer, then cross-compile the same source for the target with warnings as errors and static analysis. Where you cannot avoid hardware-specific behavior, isolate it in one small file so the rest stays testable.
Trade-offs and pitfalls
-fwrapvand-fno-strict-aliasing(the second tells the compiler not to assume that pointers of unrelated types point to different memory) are safety nets that make some UB behave predictably; they do not make the code correct, and they cost some optimization. Use them to buy time, then fix the code.- "It passes the test suite" proves nothing about UB: the optimizer decides, not the test. The same source can behave differently on a new compiler release.
- Do not write "defensive" checks that themselves rely on UB (
if (x + 1 < x)). Check the operands before the operation.
What is a dangling pointer? Show how one arises after free or from returning the address of a local variable, and how you would make the bug easier to catch in review and testing.
Sample Answer
Direct answer. A dangling pointer is a pointer whose target object no longer exists. Two common ways: after free(p) the pointer still holds the old address, and after a function returns, a pointer to one of its locals points into a stack frame that is gone. Using it is undefined behaviour: it may appear to work, print garbage, or corrupt another object. Make the bug easier to catch by compiling with warnings, running tests under AddressSanitizer, nulling pointers after free, and making ownership rules obvious in review.
Case 1: use after free
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int *returns_local(void) {
int x = 10;
return &x; /* address of an object whose lifetime ends here */
}
static void after_free(void) {
char *s = malloc(16);
strcpy(s, "hello");
free(s);
printf("%s\n", s); /* use after free */
}
int main(int argc, char **argv) {
if (argc > 1 && argv[1][0] == 'a') after_free();
else { int *p = returns_local(); printf("%d\n", *p); }
return 0;
}
Run as ./s6 a (build: gcc -g -O1 -Wall -Wextra -fsanitize=address,undefined s6.c -o s6). GCC already warns at compile time (pointer 's' used after 'free' [-Wuse-after-free]), and AddressSanitizer reports at run time:
ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000010 ...
READ of size 2 at ...
#1 ... in after_free /w/s6.c:13
0x502000000010 is located 0 bytes inside of 16-byte region [...]
freed by thread T0 here:
#1 ... in after_free /w/s6.c:12
previously allocated by thread T0 here:
#1 ... in after_free /w/s6.c:10
The report gives three stacks: the bad access (line 13), the free (line 12) and the allocation (line 10). That triple is how you fix these.
Case 2: address of a local
GCC warned function returns address of local variable [-Wreturn-local-addr] for return &x; in s6.c. Because the behaviour is undefined, the compiler may treat the returned address as anything: GCC at -O1 compiled the return to NULL, and the run crashed with a NULL read, not a stack read. This is observed behaviour, not a guarantee, and it shows that the compiler is not obliged to keep a returned stack address meaningful. To see the stack version, hide the escape from the compiler:
#include <stdio.h>
static int *saved; /* a pointer that outlives the call */
static void remember_local(void) {
int x = 10;
saved = &x; /* x dies when this function returns */
}
int main(void) {
remember_local();
printf("%d\n", *saved); /* dangling: x's frame is gone */
return 0;
}
Observed with GCC 14.4 on aarch64 Linux, same source:
gcc -O0 dangling_local.c && ./a.outprints10and exits 0. It looks correct, which is the danger.gcc -O2 dangling_local.c && ./a.outprints0and exits 0. The10is gone because nothing guarantees it is still stored: afterremember_localreturns, the stack space ofxis free for reuse, and the optimizer is also allowed to skip writing a value that the language says nobody may legally read. The program prints whatever that location holds, and the standard promises nothing about it.gcc -g -O0 -fsanitize=address dangling_local.creports (stack-use-after-return means using a local after its function returned; use-after-scope means using it after its{ }block ended)ERROR: AddressSanitizer: stack-use-after-return ... READ of size 4 ... Address ... is located in stack of thread T0 at offset 32 in frame #0 ... remember_local. In this GCC 14 build the check fired without extra options. If your toolchain does not report it, setASAN_OPTIONS=detect_stack_use_after_return=1(the Clang documentation lists this as the runtime switch).
So the same bug printed the "right" answer, a wrong answer, or a diagnostic depending on build flags: that is what undefined behaviour means in practice.
Making it easier to catch
- Compiler warnings in CI:
-Wall -Wextracaught both cases above at compile time, and they are cheap. Treat them as errors. - Sanitizers in tests: AddressSanitizer in the unit-test and fuzz builds (fuzz builds feed the code large volumes of automatically generated inputs), as shown. ASan's own documentation lists use-after-free, use-after-return and use-after-scope among the bugs it detects, at a typical slowdown it documents as about 2x.
- Null after free: a macro like
FREE_AND_NULL(p)turns a silent stale read into an immediate NULL crash:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* free + null in one place: the pointer cannot dangle through this name.
do { ... } while (0) makes the macro one statement, so `if (c) FREE_AND_NULL(p); else ...`
parses; a bare { } block followed by the `;` would break that `else` (GCC cpp manual). */
#define FREE_AND_NULL(p) do { free(p); (p) = NULL; } while (0)
struct session { char *buf; };
int main(void) {
struct session s = { malloc(16) };
struct session alias = s; /* a second copy of the pointer */
strcpy(s.buf, "token");
FREE_AND_NULL(s.buf);
printf("s.buf is %s\n", s.buf ? "live" : "NULL");
printf("alias.buf is %s\n", alias.buf ? "non-NULL (still dangling!)" : "NULL");
free(NULL); /* defined: no effect */
puts("free(NULL) is a no-op");
return 0;
}
Output (built with -fsanitize=address):
s.buf is NULL
alias.buf is non-NULL (still dangling!)
free(NULL) is a no-op
It protects only that one variable. The copy alias still dangles, which is why ownership matters more than the macro.
4. Review: ask who owns each pointer, and flag any pointer stored beyond the lifetime of the object it was derived from (a pointer into a container that may reallocate is the same bug).
5. Language help: in Rust, the compiler rejects both bug shapes before the program runs. A reference (&x, a borrow: a temporary, checked right to look at a value owned elsewhere) to a local may not outlive the function:
fn dangling() -> &'static i32 {
let x = 10;
&x
}
fn main() { println!("{}", dangling()); }
rustc 1.99.0 prints error[E0515]: cannot return reference to local variable x`` with the note "returns a reference to data owned by the current function". The second bug shape is use after free, which in Rust becomes use after a move: assigning let t = s; hands the heap text to t (a move), and s may no longer be used.
fn main() {
let s = String::from("hello");
let t = s;
println!("{} {}", s, t);
}
rustc 1.99.0 prints error[E0382]: borrow of moved value: s`` and points at the move and at the later use. In C++, owning smart pointers (objects such as std::unique_ptr that free their memory themselves) and standard containers remove most manual frees.
Pitfalls
A freed pointer is not NULL, so a if (p) guard passes. In the C standard, the value of a pointer to freed memory becomes indeterminate (it has no defined value, so any use of that value is itself undefined), so even comparing or printing it is not guaranteed. "It ran fine in testing" is the usual story, because freed memory is often untouched for a while.
A C function copies a user-supplied string into a fixed-size buffer and appends a terminator. What checks would you add to prevent off-by-one errors and overflow? Describe the logic in C rather than writing a full program.
Sample Answer
Direct answer
Reserve one byte for the terminator before you copy anything, test the bound before every read and write rather than after, and tell the caller when the input was truncated. Do not rely on strncpy to terminate for you: if the source is as long as the count, it does not (cppreference: "If count is reached before the entire array src was copied, the resulting character array is not null-terminated", https://en.cppreference.com/w/c/string/byte/strncpy).
The checks, in order
- Validate the arguments.
dstnon-NULL anddst_size > 0. A size of 0 has no room even for the terminator, so there is nothing safe to write; return an error and write nothing. - Define the contract in units of the whole buffer.
dst_sizeis the total bytes including the terminator, so the payload room isdst_size - 1. This one line prevents the classic off-by-one, because every later comparison usesroom, notdst_size. - Bound the loop on the destination, not the source. Stop when
i == roomor the source ends, whichever comes first. The source is untrusted and may be any length. - Terminate unconditionally at index
i. Because the loop stops withi <= room,dst[i]is always inside the buffer, and the result is always a valid C string. - Report truncation. If
src[i]is not'\0', input was cut. Whether to reject, truncate silently or log is a policy decision for the caller, but a function that cannot say "truncated" invites silent data corruption (a truncated path or filename can point at a different file).
Worked example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Copies src into dst (dst_size bytes in total, terminator included).
Returns 0 if everything fit, -1 if src was truncated or an argument was invalid.
When dst_size > 0 and dst is non-NULL, dst is always a valid C string afterwards. */
int copy_str(char *dst, size_t dst_size, const char *src)
{
if (dst == NULL || dst_size == 0)
return -1;
if (src == NULL) {
dst[0] = '\0';
return -1;
}
size_t room = dst_size - 1; /* bytes available for payload; 1 reserved for '\0' */
size_t i = 0;
while (i < room && src[i] != '\0') { /* the bound is tested BEFORE each read and write */
dst[i] = src[i];
i++;
}
dst[i] = '\0'; /* i <= room, so i < dst_size: always in bounds */
return src[i] == '\0' ? 0 : -1; /* anything left in src means truncation */
}
static void try(size_t size, const char *src)
{
char *dst = malloc(size ? size : 1); /* exact-size heap block so ASan sees any overrun */
int rc = copy_str(dst, size, src);
printf("size=%zu src=\"%s\" -> rc=%d dst=\"%s\"\n", size, src, rc, size ? dst : "(none)");
free(dst);
}
#ifdef BUGGY
static void buggy(const char *src)
{
size_t size = 4;
char *dst = malloc(size);
strncpy(dst, src, size); /* copies 4 bytes, no terminator when src is longer */
dst[size] = '\0'; /* off-by-one: index 4 of a 4-byte block */
printf("buggy copy: \"%s\"\n", dst);
free(dst);
}
#endif
int main(void)
{
try(8, "hello"); /* fits with room to spare */
try(6, "hello"); /* exact fit: 5 chars + terminator */
try(5, "hello"); /* one short: truncated to "hell" */
try(1, "hello"); /* only room for the terminator */
try(0, "hello"); /* no room at all */
try(4, ""); /* empty source */
#ifdef BUGGY
buggy("hello");
#endif
return 0;
}
Compiled with gcc -O2 -Wall -Wextra -fsanitize=address,undefined copy.c in a Linux arm64 container (GCC 14.4.0) and run, the output is:
size=8 src="hello" -> rc=0 dst="hello"
size=6 src="hello" -> rc=0 dst="hello"
size=5 src="hello" -> rc=-1 dst="hell"
size=1 src="hello" -> rc=-1 dst=""
size=0 src="hello" -> rc=-1 dst="(none)"
size=4 src="" -> rc=0 dst=""
Each case uses a malloc block of exactly size bytes, so AddressSanitizer would flag any single byte written past the end. The test cases target the boundaries: exact fit (6 bytes for 5 characters), one short, only-terminator room, zero room, empty input.
The bug this prevents
The tempting version is strncpy(dst, src, size); dst[size] = '\0';. Compiling that variant with -DBUGGY (it is in the listing above) at -O2 (GCC 14.4.0, arm64), GCC warned array subscript 4 is outside array bounds of 'char[4]' [-Warray-bounds=] (that warning appears only at -O2; at -O1 GCC instead warns 'strncpy' output truncated copying 4 bytes from a string of length 5 [-Wstringop-truncation], and at -O0 it prints no warning), and with -fsanitize=address the run was reported as a write 0 bytes after a 4-byte region. The correct form of the strncpy idiom writes the terminator at dst[size - 1], but that still pads and scans the full buffer and cannot tell you about truncation, so the explicit loop above is clearer.
Alternatives and when to choose them
snprintf(dst, size, "%s", src): always terminates whensize > 0and returns the length it would have written, soret >= sizemeans truncation. Good default when you are already allowed to usesnprintf; remember a negative return is an error.memcpyafter computingn = strlen(src): only if you already knowsrcis terminated;strlenon an unterminated untrusted buffer is itself an overread. Bound it with a known maximum length first.- Length-carrying types (a pointer plus length, or
std::string_viewin C++) remove the problem where you control the interface.
Trade-offs and pitfalls
- Off-by-one comes from mixing "capacity" and "length" in the same expression; name them separately.
- Check the return value. A bounded copy that nobody checks is a silent truncation bug.
- Validate the content too: a correctly bounded copy of a string with an embedded newline or
../can still be an injection.
A loop like for (int i = 0; i <= n; ++i) was merged into a C code path where n is the number of valid array elements. The code sometimes works in testing and sometimes crashes in production. What makes this pattern dangerous in C, and how can it turn into a harder-to-debug memory bug than a simple out-of-bounds read?
Sample Answer
Direct answer. In C, an array of n elements has valid indexes 0 through n - 1. The loop for (int i = 0; i <= n; ++i) runs one time too many and touches element n, one past the end. That is undefined behaviour (UB: the language gives no guarantee, so the program may crash, work, or misbehave later). Because it often lands on memory that is legitimately owned by something else, the result depends on layout, compiler options and the allocator, which is why it passes tests and fails in production. It is worse than an out-of-bounds read because a write silently corrupts a neighbour: another field, a saved register (a value the CPU parked on the stack to restore when the function returns), or the allocator's own bookkeeping (the chunk headers described in layout 3 below), and the failure appears later, somewhere unrelated.
Why the symptoms vary
Three real layouts, each tested below, show the same bug looking completely different.
1. Neighbour inside the same object. If the array is followed by another field, the extra write lands on it, and nothing is "out of bounds" as far as the hardware or the heap is concerned.
#include <stdio.h>
#include <stdlib.h>
/* Neighbour inside the same object: the overrun lands on a field that is "valid memory". */
struct stats {
int samples[4];
int limit; /* sits right after the array */
};
int main(void) {
struct stats s = { .samples = {0}, .limit = 100 };
int n = 4; /* 4 valid elements: indexes 0..3 */
for (int i = 0; i <= n; ++i) /* BUG: writes samples[4] */
s.samples[i] = -1;
printf("limit after loop = %d (expected 100)\n", s.limit);
return 0;
}
Built and run in a Linux container (GCC 14.4, aarch64):
$ gcc -O0 overrun_struct.c -o a0 && ./a0
limit after loop = -1 (expected 100)
$ gcc -O2 overrun_struct.c -o a2 && ./a2
overrun_struct.c: In function 'main':
overrun_struct.c:14:22: warning: iteration 4 invokes undefined behavior [-Waggressive-loop-optimizations]
14 | s.samples[i] = -1;
| ~~~~~~~~~~~~~^~~~
overrun_struct.c:13:23: note: within this loop
13 | for (int i = 0; i <= n; ++i) /* BUG: writes samples[4] */
| ~~^~~~
limit after loop = 100 (expected 100)
$ gcc -O2 -g -fsanitize=address,undefined overrun_struct.c -o aa && ./aa
overrun_struct.c:14:18: runtime error: index 4 out of bounds for type 'int [4]'
limit after loop = 100 (expected 100)
The same source corrupts limit at -O0 and appears correct at -O2. At -O2 the compiler assumes the store to samples[4] cannot be a legal access to limit and may assume the undefined iteration never happens (GCC says so in its warning); in the generated aarch64 code the printf argument is simply the constant 100 (mov w1, 100), so limit is never even reloaded from the corrupted memory. A test build and a release build can therefore disagree. Note that UBSan (UndefinedBehaviorSanitizer, which checks array bounds when it knows the array size) caught this one, while ASan, which watches heap, stack-frame and global boundaries and not fields inside one object, did not.
2. Slack in the heap block. malloc rounds up. Measured on glibc 2.41 (the Debian 13 container, both aarch64 and x86-64):
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 4;
for (int bytes = 16; bytes <= 40; bytes += 8) {
void *p = malloc((size_t)bytes);
printf("malloc(%d) usable size = %zu\n", bytes, malloc_usable_size(p));
free(p);
}
(void)n;
return 0;
}
malloc(16) usable size = 24
malloc(24) usable size = 24
malloc(32) usable size = 40
malloc(40) usable size = 40
(gcc -O2 usable_size.c -o c && ./c.) An array of four int (16 bytes) has 8 spare bytes, so writing heap[4] lands in slack and nothing visibly breaks. That is the "works in testing" case.
3. No slack: the allocator's own header. glibc hands out memory in chunks: each block you get from malloc is preceded by a small header (the allocator's bookkeeping) holding, among other things, the block's size, which free reads to know what it is releasing. Laid out in memory: [header: size][your 24 bytes][next chunk's header: size][next block ...]. With six int (24 bytes, exactly the usable size), element 6 overwrites the first bytes of the next chunk's header:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n = 6; /* 6 ints = 24 bytes = the whole usable size */
int *a = malloc(n * sizeof *a);
int *b = malloc(n * sizeof *b);
if (!a || !b) return 1;
for (int i = 0; i <= n; ++i) /* BUG: a[6] lands on the next chunk's size field */
a[i] = -1;
printf("loop finished, nothing crashed yet\n");
fflush(stdout);
free(a);
printf("free(a) returned\n");
fflush(stdout);
free(b);
printf("freed\n");
return 0;
}
$ gcc -O0 overrun_heap.c -o d && ./d
loop finished, nothing crashed yet
free(a) returned
munmap_chunk(): invalid pointer
Aborted
$ gcc -O0 -g -fsanitize=address overrun_heap.c -o da && ./da
==18==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x503000000058 at pc ...
WRITE of size 4 at 0x503000000058 thread T0
#0 0x400ac4 in main /w/overrun_heap.c:10
The loop and free(a) both succeed. The process dies at free(b), because the -1 clobbered the size field that free trusts. munmap_chunk(): invalid pointer is glibc's message for a block whose recorded size and flags made it take the wrong release path and then fail its own sanity check; the text means "the header of this block is not what I wrote", and it says nothing about which line damaged it. The crash is in a different statement from the bug, in code that looks correct, and the message is glibc-version specific. This is why the bug is harder to diagnose than a bad read: a read returns a wrong value at the faulty line, a write breaks something that is used later. On the stack the same overrun can hit a neighbouring local, a saved frame pointer (the caller's frame address, kept on the stack) or a return address, which is why MITRE's CWE-193 (an entry in the Common Weakness Enumeration, the public catalogue of software weakness types; this one is the off-by-one error) notes that it can lead to memory corruption and sometimes arbitrary code execution, not just a crash.
How to find it and prevent it
- Compile with
-Wall -Wextra -O2and read warnings; the-Waggressive-loop-optimizationsmessage above names the exact iteration. - Run tests under ASan and UBSan (
-fsanitize=address,undefined), and make sure at least one test runs with a full-size input, since the bug needs the last iteration to execute. - Reproduce in the debugger with a hardware watchpoint (a CPU feature that halts the program the moment a chosen address is written) on the corrupted field (
watch s.limitin gdb orwatchpoint set variablein lldb) to see which line writes it. - Fix the bound,
i < n, and prefersize_tfor indexes and counts so a negativencannot slip through a signed comparison. Derivenfromsizeof a / sizeof a[0]when the array is local, so the count cannot drift from the declaration.
Trade-offs and pitfalls
A condition written <= n is correct when n is the last valid index and wrong when it is the count, so name variables count or last and the loop reads correctly. Adding a canary or padding to hide the symptom is not a fix: it only moves where the write lands. Treat "works on my machine, at this optimization level" as no evidence at all for code with UB.
Unlock Full Question Bank
Get access to all 32 Language-Level Memory Management (C/C++/Rust) interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.