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.
A parser builds a heap-allocated char ** list of tokens and hands it to the caller. Some tokens are duplicated strings, and some are slices into a larger buffer. How would you design the ownership rules and cleanup path so the caller can safely filter or free the result without leaks or double frees?
Sample Answer
Direct answer. A char ** whose entries have mixed ownership cannot be cleaned up safely, because nothing in the type says which entries to free. I would not build it. I would give the whole result one owner and one release call: every token that survives to the caller lives inside a single allocation (or an object that owns everything), tokens never need individual freeing, and filtering means rearranging pointers, not freeing. If some callers truly need to keep a token after the list is gone, they copy that one token explicitly. If zero-copy slices (views into the caller's own buffer that copy nothing) are wanted, they are exposed as a different type, a pointer plus a length that is documented to be valid only while the source buffer lives, never mixed into an array of owned strings.
Why the mixed array fails
Duplicated strings (made with strdup, i.e. malloc plus copy) must be freed. Slices point into someone else's buffer and must not be freed. A cleanup loop that frees every entry hits a slice and crashes, and a loop that frees none leaks the duplicates. A slice also is not a C string unless the buffer was modified to put a NUL after it. Here is the obvious loop run under AddressSanitizer (ASan):
#include <stdlib.h>
#include <string.h>
int main(void) {
char *buf = strdup("one two");
char **list = malloc(3 * sizeof *list);
list[0] = strdup("owned"); /* duplicated: must be freed */
list[1] = buf + 4; /* slice into buf: must NOT be freed */
list[2] = NULL;
for (size_t i = 0; list[i]; ++i) /* the obvious cleanup loop */
free(list[i]);
free(list);
free(buf);
return 0;
}
=================================================================
==19==ERROR: AddressSanitizer: attempting free on address which was not malloc()-ed: 0x502000000014 in thread T0
#0 0xffff83ce2dec (/usr/local/lib64/libasan.so.8+0xd2dec)
#1 0x400a7c in main /w/tokens_bad.c:11
(gcc -g -O0 -fsanitize=address tokens_bad.c -o bad && ./bad. The report is trimmed here: paths are shortened and it continues with the remaining stack frames, a line saying the address is 4 bytes inside an 8-byte region, the strdup allocation site and a SUMMARY: AddressSanitizer: bad-free line. The PID and addresses differ between runs.) Even when the bug does not crash, a caller that filters the list has to know, per entry, whether to free a dropped token, and that knowledge exists nowhere in the data.
Design options and the choice
| Option | Cleanup rule | Filtering | Verdict |
|---|---|---|---|
Per-entry owned flag in a struct | free the flagged ones | must free dropped owned entries, keep flags aligned when compacting | works, but every caller and every filter must get the flag handling right |
| Everything is a slice (pointer + length) of the caller's buffer | free nothing | trivial | needs the source buffer to outlive the list; slices are not NUL-terminated |
| One owner: all tokens copied into one block | one free(list) | compact the pointer array, free nothing | simplest contract for a char ** result |
Opaque handle (a pointer to a struct whose fields the caller cannot see) with tokens_free(h) and accessor functions (small getter functions such as tokens_count(h) and tokens_get(h, i)) | one call | provided by the API | best when tokens are added or transformed later |
My recommendation is the one-block layout for a plain char ** result, and the opaque handle if the API will grow. Copying costs one pass over the input, and it removes the whole class of lifetime bugs: the caller's input buffer may be freed or modified immediately afterwards. If profiling shows the copy matters, switch to the pointer-plus-length view type and keep it separate from the owning type.
Implementation
The block is [ n+1 pointers ][ n NUL-terminated token copies ]. For the input "alpha,,beta,gamma," there are 4 separators, so n = 5 tokens (two of them empty); the string is 18 characters, of which 14 are token characters (5 + 0 + 4 + 5 + 0), so the copies need 14 + 5 NULs = 19 bytes, which is strlen(s) + 1, because every separator turns into the NUL that ends the token before it. The pointer array needs 6 pointers (5 tokens plus the NULL terminator). The tokens that would have been "slices" and the ones that would have been "duplicates" are all just regions of the block, so there is only one kind of token.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Split s on sep. Returns a NULL-terminated char ** that lives in ONE malloc block:
[ n+1 pointers ][ n NUL-terminated token copies ]
Every token is owned by that block. The caller releases everything with a single free(list).
Returns NULL on allocation failure (nothing to free). */
char **tok_split(const char *s, char sep) {
size_t n = 1; /* n tokens: separators + 1 */
for (const char *p = s; *p; ++p) { if (*p == sep) n++; }
/* Each separator becomes the NUL ending the token before it, and the last token
gets the input's own terminator, so the string area is exactly strlen(s) + 1 bytes. */
size_t bytes = strlen(s) + 1;
/* Overflow guard: (n + 1) * sizeof(char *) + bytes must not exceed SIZE_MAX.
Rearranged to avoid multiplying: n + 1 <= (SIZE_MAX - bytes) / sizeof(char *). */
if (n + 1 > (SIZE_MAX - bytes) / sizeof(char *)) return NULL;
char **list = malloc((n + 1) * sizeof *list + bytes);
if (!list) return NULL;
char *dst = (char *)(list + n + 1); /* string area starts after the pointer array */
size_t i = 0;
const char *start = s;
for (const char *p = s;; ++p) {
if (*p == sep || *p == '\0') {
size_t len = (size_t)(p - start);
memcpy(dst, start, len);
dst[len] = '\0';
list[i++] = dst;
dst += len + 1;
start = p + 1;
if (*p == '\0') break;
}
}
list[i] = NULL;
return list;
}
/* Keep only tokens for which keep() is non-zero. Compacts the pointer array in place,
keeps the NULL terminator, frees nothing (the bytes stay in the block until free(list)).
Returns the new count. */
size_t tok_filter(char **list, int (*keep)(const char *)) {
size_t w = 0;
for (size_t r = 0; list[r]; ++r)
if (keep(list[r])) list[w++] = list[r];
list[w] = NULL;
return w;
}
static int non_empty(const char *t) { return t[0] != '\0'; }
static void dump(const char *label, char **list) {
printf("%s:", label);
for (size_t i = 0; list[i]; ++i) printf(" [%s]", list[i]);
printf("\n");
}
int main(void) {
char input[] = "alpha,,beta,gamma,";
char **t = tok_split(input, ',');
if (!t) return 1;
dump("split", t);
input[0] = 'X'; /* caller's buffer changes: tokens are copies */
dump("after editing the input buffer", t);
size_t kept = tok_filter(t, non_empty);
printf("kept %zu\n", kept);
dump("filtered", t);
free(t); /* one call releases pointers and bytes */
char **e = tok_split("", ',');
if (!e) return 1;
dump("empty input", e);
printf("count = %zu\n", tok_filter(e, non_empty));
free(e);
return 0;
}
Built and run in a Linux container (GCC 14.4, aarch64) with gcc -O2 -Wall -Wextra -g -fsanitize=address,undefined tokens.c -o tokens && ./tokens (exit status 0, and ASan's leak checker, LeakSanitizer, reported nothing):
split: [alpha] [] [beta] [gamma] []
after editing the input buffer: [alpha] [] [beta] [gamma] []
kept 3
filtered: [alpha] [beta] [gamma]
empty input: []
count = 0
The ownership contract to document
tok_splitreturns NULL on failure (nothing to free) or a list the caller owns; the only release isfree(list), exactly once, and the list must not berealloced.- Tokens are valid until
free(list). Pointers into the list stay valid aftertok_filter, but dropped tokens' bytes remain in the block until then. Pointers to a token must not outlive the list; copy withstrdupif a token must. tok_filternever frees and never allocates, so it cannot fail halfway and cannot double-free. It keeps the terminating NULL, so loops written asfor (i = 0; list[i]; i++)stay valid.- The input buffer is only read: the test shows editing it afterwards does not change the tokens.
- Failure behaviour: the size arithmetic is checked for overflow before
malloc(the guard asks whether(n + 1)pointers plusbytescharacters can exceedSIZE_MAX, rewritten as a division so the check itself cannot overflow), and a failed allocation returns NULL with no partial result.
Pitfalls and trade-offs
The one-block layout means memory for filtered-out tokens is held until the whole list is freed, which is fine for short-lived lists and wrong for a long-lived one that is filtered to a tiny subset; then copy the survivors into a new block and free the old one. It also hands out char * into a block shared by every token, so a caller that writes past the end of one token corrupts its neighbour; mark tokens const char * in the public header to say they are read-only. In C++ the same contract is std::vector<std::string> (everything owned) or std::vector<std::string_view> with the source's lifetime documented, and the compiler enforces the cleanup.
A C function returns a pointer to a buffer. What are the ownership and lifetime implications when it returns a pointer to a local automatic variable, a pointer to a static local variable, and a pointer obtained from malloc, and how would you document or enforce who must free what?
Sample Answer
Direct answer. A pointer returned from a C function has three different ownership stories depending on where it points: a pointer to a local automatic variable (one declared inside the function with the default, non-static storage, which lives only inside that one call's stack frame: the block of memory set aside for that call's local variables) is always wrong (the storage is gone the instant the function returns), a pointer to a static local variable is valid forever but shared by every caller (not reentrant, meaning a second call before the first caller is done with the result corrupts it; not thread-safe, meaning two threads calling concurrently race on it), and a pointer from malloc is valid until freed and ownership transfers to the caller, who must free it exactly once. Document and enforce which one you have with the function's naming convention, its return-value contract, and, for the heap case, an explicit paired free function.
Case 1: pointer to a local automatic variable. The variable's storage is the function's stack frame, which has automatic storage duration (allocated when the function is entered, deallocated the moment it returns, with no action from the programmer either way). That deallocation happens before the caller even gets the returned pointer back. Any use of that pointer afterward reads memory that may be overwritten by the very next function call. This is never valid and has no legitimate use; the fix is always one of the other two options.
Case 2: pointer to a static local variable. static inside a function gives the variable the same storage duration as a global: it is allocated once and lives for the entire program, so the returned pointer stays valid forever. The catch is there is exactly one instance shared by every call: a second call before you are done with the first call's result overwrites the same memory, and two threads calling concurrently race on it. This pattern is common in legacy APIs (classic ctime, asctime, localtime, which return a pointer into one static buffer; strtok keeps its position in static state) specifically because it needs no caller-side cleanup, but it is not reentrant (safe to call again, from the same or another thread, before a previous call's result is done being used) and not thread-safe, which is exactly why POSIX added _r (reentrant) variants such as ctime_r and strtok_r that keep the state or the result in caller-supplied storage instead.
Case 3: pointer from malloc. The block is valid until explicitly freed, and by convention the function that returns it transfers ownership to the caller: the caller, and only the caller, is responsible for calling free() on it exactly once. This is the most flexible case (each call gets its own independent, arbitrarily-lived block) but also the one with the most ways to get wrong: forgetting to free (leak), freeing twice (double free, undefined behavior), or the caller assuming it does NOT own the pointer when the function's contract actually says it does.
How to document and enforce ownership. Three mechanisms, from weakest to strongest:
- Naming convention, visible at every call site: a function that returns a heap pointer the caller must free is named so that is obvious (
*_new,*_create,*_dup), paired with an equally obvious*_free/*_destroy. A function returning a static-local or borrowed pointer avoids an allocation-sounding name so callers do not reflexively free it. - Comment/doc contract at the declaration, stating explicitly who owns the return value and its lifetime ("caller must free", "valid until the next call to this function", "valid for the lifetime of
ctx"). - A paired API plus tooling: C's type system cannot express ownership (a
char *looks the same whether or not the caller must free it), so the strongest options are a_create/_destroypair on an opaque handle type (the caller never sees inside it, so the only way to release it is the matching_destroy), together with tools that catch violations (ASan/LeakSanitizer catch leaked or double-freed blocks at test time;-fanalyzer, a GCC static analysis pass, and Clang's static analyzer can flag some missing-free paths at compile time without even running the code).
Worked example: all four return shapes side by side.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char *label_local(int n) { /* case 1: local automatic array */
char buf[16];
snprintf(buf, sizeof buf, "item-%d", n);
return buf; /* returns address of a dead stack frame */
}
static const char *label_static(int n) { /* case 2: static local */
static char buf[16];
snprintf(buf, sizeof buf, "item-%d", n);
return buf;
}
static char *label_new(int n) { /* case 3: heap, caller frees */
char *p = malloc(16);
if (!p) return NULL;
snprintf(p, 16, "item-%d", n);
return p;
}
static void label_into(char *out, size_t cap, int n) { /* case 4: caller-provided buffer */
snprintf(out, cap, "item-%d", n);
}
int main(void) {
const char *l = label_local(1);
printf("local ptr=%p\n", (const void *)l);
const char *a = label_static(1), *b = label_static(2);
printf("a=%s b=%s same pointer: %s\n", a, b, a == b ? "yes" : "no");
char *c = label_new(1), *d = label_new(2);
printf("c=%s d=%s same pointer: %s\n", c, d, c == d ? "yes" : "no");
free(c); free(d);
char buf4[16]; label_into(buf4, sizeof buf4, 7);
printf("buf4=%s\n", buf4);
return 0;
}
Compiled with GCC 14 (gcc -Wall -Wextra at -O0 and at -O2, and -O1 -fsanitize=address,undefined, Linux arm64, in a container), the compiler says warning: function returns address of local variable [-Wreturn-local-addr] on label_local before the program ever runs, which is case 1 caught by the compiler itself. At run time label_local returned NULL at every optimization level (local ptr=(nil)): GCC itself substitutes a null pointer for the returned address of a local, because returning it is undefined behavior and the compiler may do anything; it is not a stack slot that happened to be reused. ASan reported nothing for the same reason, since no dead-stack address is ever dereferenced. Do not rely on that: a different compiler or version may return the dangling address and let you read garbage, which is the worse failure because it looks like it works. The remaining lines of the same run:
local ptr=(nil)
a=item-2 b=item-2 same pointer: yes
c=item-1 d=item-2 same pointer: no
buf4=item-7
label_static(1) then label_static(2) return the same address, and by the time both results are printed the first call's content has been overwritten (a=item-2 b=item-2 same pointer: yes), demonstrating the shared-buffer hazard directly, not just asserting it. label_new(1) and label_new(2) each get a distinct heap block (c=item-1 d=item-2 same pointer: no), which is correct only because each result is freed exactly once by the caller afterward. label_into (case 4, the caller-provided-buffer style, which sidesteps the whole ownership question because the caller already owns the only buffer involved) fills the caller's own buf4 directly (buf4=item-7), with no allocation and no lifetime question at all, the style you reach for when you want to avoid every pitfall above by construction.
Trade-offs and pitfalls. The static-local pattern's hazard is easy to miss in code review because it looks identical to the heap case at the call site (const char *x = some_func(...)); the only way to know which contract you are under is documentation or the naming convention, which is exactly why that discipline matters more here than in the other two cases. Never let a function sometimes return a heap pointer and sometimes a static or literal pointer depending on a branch: that forces every caller to guess per-call whether to free, which is unfixable by convention alone and should be refactored into two differently-named functions. When in doubt about an unfamiliar API's return value, check the documentation before freeing it speculatively: freeing a pointer that was not heap-allocated (a string literal, a static buffer, a pointer into a caller-owned buffer) is undefined behavior, not a safe no-op.
Which tools and compiler or runtime options would you use to find memory leaks, out-of-bounds accesses, and use-after-free bugs in a C or C++ codebase, and how do you interpret their output when triaging a suspected bug?
Sample Answer
Direct answer. Start with compiler warnings (-Wall -Wextra), then build the tests and a fuzzing harness (a fuzzer feeds a program huge numbers of automatically generated or mutated inputs, and the harness is the small entry point that hands each input to the code under test) with AddressSanitizer plus UndefinedBehaviorSanitizer (-fsanitize=address,undefined -g -fno-omit-frame-pointer); AddressSanitizer includes LeakSanitizer on Linux. For binaries you cannot rebuild, or to see uninitialized reads, run under Valgrind's Memcheck (a tool that runs your unmodified program under its own checker, watching every memory access). Read each report in the same order: error type, the access (read or write, size), the faulting stack with file and line, then the allocation and free stacks, and only then decide the fix.
What each tool is for
Start with AddressSanitizer plus UndefinedBehaviorSanitizer in one build; the other rows cover what they do not.
| Tool | Flag | Catches (per the vendors' documentation) |
|---|---|---|
| AddressSanitizer (ASan) | -fsanitize=address | out-of-bounds on heap, stack and globals; use-after-free, -return and -scope; double and invalid free; leaks |
| LeakSanitizer | on by default with ASan on Linux; or -fsanitize=leak | memory that is never freed and unreachable at exit |
| UndefinedBehaviorSanitizer (UBSan) | -fsanitize=undefined | signed overflow, null dereference and other UB, each printed as runtime error: |
| Valgrind Memcheck | valgrind --leak-check=full ./prog | invalid reads and writes, use of uninitialised values, bad frees, mismatched malloc/delete, leaks |
| GCC documents that address and thread sanitizers cannot be combined, so run ThreadSanitizer (which finds data races: two threads using the same memory without synchronisation, at least one writing) in a separate build. ASan's documentation lists a typical slowdown of 2x, so it is practical for CI test runs, not production. The ASan, LeakSanitizer and UBSan rows were run in a GCC 14.4 container, and Memcheck (Valgrind 3.24.0, installed with apt in the same kind of container) in its own run shown below. |
One program, four bugs
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(int argc, char **argv) {
int which = argc > 1 ? atoi(argv[1]) : 0;
int *a = malloc(4 * sizeof *a);
if (which == 1) a[4] = 1; /* heap overflow by one element */
else if (which == 2) { int big = INT_MAX; big += argc; printf("%d\n", big); } /* signed overflow */
else if (which == 3) { free(a); a[0] = 1; a = NULL; } /* use after free */
else if (which == 4) { a = NULL; } /* leak */
if (which != 3 && which != 4) free(a);
return 0;
}
Built with gcc -g -O1 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer s8.c -o s8, run as ./s8 N: (the reports below are trimmed: libc and runtime-library frames, the pointer points here hex dump and the shadow-byte map are left out, and ... marks other elisions. The compiler also prints a -Wuse-after-free warning for the which == 3 line, which is the first hint of that bug.)
./s8 1 (heap overflow, one int past a 4-element array):
s8.c:7:26: runtime error: store to address 0x502000000020 with insufficient space for an object of type 'int'
ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000020 ...
WRITE of size 4 at 0x502000000020 thread T0
#0 ... in main /w/s8.c:7
0x502000000020 is located 0 bytes after 16-byte region [0x502000000010,0x502000000020)
allocated by thread T0 here:
#1 ... in main /w/s8.c:6
./s8 2 (UBSan; note the program keeps running and prints the wrapped value):
s8.c:8:51: runtime error: signed integer overflow: 2 + 2147483647 cannot be represented in type 'int'
-2147483647
./s8 3 (use after free): ERROR: AddressSanitizer: heap-use-after-free ... WRITE of size 4, then freed by thread T0 here at line 9 and previously allocated by thread T0 here at line 6.
./s8 4 (leak): ERROR: LeakSanitizer: detected memory leaks and Direct leak of 16 byte(s) in 1 object(s) allocated from: ... main /w/s8.c:6, with SUMMARY: AddressSanitizer: 16 byte(s) leaked in 1 allocation(s).
Valgrind Memcheck on the same kind of bugs
Valgrind needs no rebuild, but its manual asks for -g so messages carry line numbers, and it warns the program runs much slower (20 to 30 times) and that Memcheck cannot detect out-of-range accesses to static or stack arrays. A small program (saved as vg.c, so the line numbers below count the two #include lines), built with gcc -g -O0 vg.c -o vg and run as valgrind --leak-check=full ./vg N (arm64 Linux):
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int which = argc > 1 ? atoi(argv[1]) : 0;
int *a = malloc(4 * sizeof *a);
if (which == 1) a[4] = 1; /* heap overflow by one element */
else if (which == 2) { int u; if (u > argc) puts("big"); } /* uninitialized read */
free(a);
return 0;
}
$ valgrind --leak-check=full ./vg 1
==197== Invalid write of size 4
==197== at 0x400760: main (vg.c:6)
==197== Address 0x4a7f050 is 0 bytes after a block of size 16 alloc'd
==197== at 0x488545C: malloc (vg_replace_malloc.c:446)
==197== by 0x400743: main (vg.c:5)
$ valgrind --leak-check=full ./vg 2
==201== Conditional jump or move depends on uninitialised value(s)
==201== at 0x400780: main (vg.c:7)
The first report reads like ASan's: an invalid write of 4 bytes, directly after a 16-byte block allocated at line 5. The second is the kind of bug ASan's documented list does not cover: a branch decided by a variable that was never set. (Both Memcheck reports are trimmed to their error blocks: the startup banner, HEAP SUMMARY and ERROR SUMMARY lines are left out. ==197== is the process id; the addresses are illustrative.)
How to read a report
- Headline:
heap-buffer-overflow,heap-use-after-free,stack-buffer-overflow,attempting double-free,SEGV on unknown address. This names the class. - Access line:
WRITE of size 4. A write is more dangerous than a read (corruption, possibly exploitable). - First stack: the first frame in your code is where the bad access happened. Frames inside the runtime library are noise.
- Region line:
located 0 bytes after 16-byte regionmeans a one-past-the-end overflow (off-by-one loop or<=). A large offset means a wild index or a wrong length.0 bytes insideplus a "freed by" stack means use after free. - Second and third stacks: who freed it and who allocated it. For use-after-free the question is why a pointer outlived the free: it is almost always a second owner.
- Leaks:
Direct leakis a block no pointer reaches, with the allocation stack and size. Leaks are reported at exit, so exit the program cleanly in tests.
Triage order for a suspected bug
- Reproduce with a sanitizer build and the failing input. If it fails only without the sanitizer, suspect an uninitialised read: Memcheck reports those, and ASan's documented list does not include them.
- Read the report in the order given in the previous section and fix the first reported error; later ones are often consequences.
- Add the failing input as a regression test and keep the sanitizer build in CI.
- Check for a false positive only after the report's allocation and free stacks fail to make sense; remember ASan's own HINT line: it may be a false positive if the program uses a custom stack unwind mechanism (code that jumps around the stack on its own),
swapcontext(saves the current execution context and switches to another, which gives it its own stack) orvfork(creates a child process that shares the parent's memory, stack included, until it execs or exits).
Pitfalls
- No
-gor an optimized-away frame pointer (the register compilers keep pointing at the current call's frame, which tools follow to list the callers;-fno-omit-frame-pointerkeeps it) gives hex offsets with no line numbers. - A clean sanitizer run proves nothing about inputs the tests never reached; pair sanitizers with a fuzzer or realistic corpora.
- Sanitizers change memory layout and timing; a bug that only shows without them still needs a debugger and a core dump (the file the operating system writes when a process crashes, holding an image of its memory at that moment, which a debugger such as gdb can open).
Design a C or C++ plugin interface where a host loads third-party modules and passes buffers and callbacks across the module boundary. What ownership and lifetime contract would you enforce between host and plugin?
Sample Answer
Direct answer. I would make the boundary a plain C ABI (application binary interface: the binary-level rules for calling and data layout) with a small, versioned table of function pointers, and enforce one rule everywhere: whoever allocates a block releases it, through the same module's code, and every pointer that crosses the boundary has a stated lifetime. Buffers handed in for a call are borrowed for that call only, buffers handed out are either filled into caller-provided memory or allocated through a host-provided allocator, an instance has a creation and a single destruction call, callbacks carry a context pointer and are only valid while the instance lives, and the host never unloads the library before the plugin has been destroyed. Plugins are shared libraries (.so files on Linux): code the host loads at run time with dlopen, finds functions in by name with dlsym, and unloads with dlclose. Nothing C++-specific (exceptions, std::string, STL containers, virtual calls) crosses the boundary, because the plugin may be built with a different compiler, standard library or allocator.
Why the contract has to be this strict
A host and a third-party plugin are separately compiled and share one process and its address space (the memory the process can see), so they may use different C runtimes and different malloc implementations. Freeing a plugin's block with the host's free (or the reverse) can corrupt the heap. A pointer to a stack buffer saved by the plugin for later is a dangling pointer (one that still holds an address after the memory behind it has been released or reused) once the call returns. A callback pointing into a library that has been unloaded jumps into unmapped memory (address space the operating system has taken back, so any access faults). These are the failures the rules prevent.
The interface
#ifndef PLUGIN_API_H
#define PLUGIN_API_H
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define PLUGIN_ABI_VERSION 1u
enum plugin_status { PLUGIN_OK = 0, PLUGIN_ERR = -1, PLUGIN_TOO_SMALL = -2 };
/* Services the host lends to a plugin. Valid from create() until destroy() returns. */
typedef struct host_api {
uint32_t size; /* sizeof(host_api) as the host built it */
void *(*alloc)(void *host_ctx, size_t n); /* memory the HOST will free, or the plugin frees via free_mem */
void (*free_mem)(void *host_ctx, void *p);
void (*log)(void *host_ctx, const char *msg); /* msg borrowed for the call only */
void *host_ctx; /* passed back on every callback */
} host_api;
/* What the plugin exports. The plugin owns this table; it lives as long as the library stays loaded. */
typedef struct plugin_api {
uint32_t size;
uint32_t abi_version;
void *(*create)(const host_api *host, const char *config); /* config borrowed; plugin copies what it keeps */
int (*process)(void *inst, const uint8_t *in, size_t in_len,
uint8_t *out, size_t out_cap, size_t *out_len);
void (*destroy)(void *inst); /* exactly once, then inst is dead */
} plugin_api;
/* The only symbol the host looks up by name. Returns NULL if abi_version is unsupported. */
const plugin_api *plugin_get_api(uint32_t host_abi_version);
#ifdef __cplusplus
}
#endif
#endif
The rules, stated as a contract
| Rule | What it means in this API |
|---|---|
| Single entry point | the host looks up only plugin_get_api by name and passes its ABI version; the plugin returns NULL if it does not support it, so a version mismatch is a clean failure |
| Versioned, sized structs | size fields let the host check the plugin's table is at least as large as it expects, and let the plugin check the host table; new fields are appended, never reordered |
| Allocate and free on the same side | memory the plugin needs from the host comes through host_api.alloc and goes back through free_mem; the plugin never calls the host's free on its own pointers or the reverse |
| Borrowed inputs | config and in are valid only during the call; the plugin copies what it keeps (it copied config into its own allocation) |
| Caller-provided output with a size query | process writes into out of capacity out_cap, always sets *out_len to the size needed, and returns PLUGIN_TOO_SMALL without writing when it does not fit, so no ownership transfer is needed |
| Instance lifetime | create returns an opaque inst (a void * whose contents only the plugin understands: the host stores it and passes it back, and never looks inside; NULL on failure, with partial initialization undone), destroy is called exactly once, and no call may use inst afterwards |
| Callback lifetime | host_api callbacks and host_ctx are valid from create until destroy returns; the plugin copies the table because the host's struct is borrowed |
| No exceptions across the boundary | a C++ exception unwinding into frames built by another compiler or language, or a longjmp over frames that own C++ objects, can skip cleanup or terminate the process (the C++ standard leaves a longjmp that would bypass non-trivial destructors undefined); catch at the border and return a status |
| Unload last | the host calls dlclose only after destroy, since the plugin's functions and the callbacks it registered live in that library |
| Threading | state in the header which threads may call process (here: one at a time per instance, no concurrent calls) |
Host and plugin, built and run
The plugin keeps its state in struct instance. Two lines are easy to miss: in->host = *host copies the host's callback table into the instance, because the host's own table is only borrowed for the create call; and host_api h = in->host in p_destroy copies it back out to a local before freeing, because in is about to be freed and the final free_mem call still needs the callback and host_ctx.
#include "plugin_api.h"
#include <ctype.h>
#include <string.h>
struct instance {
host_api host; /* copy: host's table is borrowed, ours is not */
char *prefix; /* copy of config, allocated through the host */
};
static void *p_create(const host_api *host, const char *config) {
if (!host || host->size < sizeof(host_api) || !config) return NULL;
struct instance *in = host->alloc(host->host_ctx, sizeof *in);
if (!in) return NULL;
in->host = *host;
size_t n = strlen(config) + 1;
in->prefix = host->alloc(host->host_ctx, n);
if (!in->prefix) { host->free_mem(host->host_ctx, in); return NULL; } /* undo partial init */
memcpy(in->prefix, config, n);
host->log(host->host_ctx, "plugin: created");
return in;
}
static int p_process(void *inst, const uint8_t *in_buf, size_t in_len,
uint8_t *out, size_t out_cap, size_t *out_len) {
struct instance *in = inst;
size_t plen = strlen(in->prefix);
size_t need = plen + in_len;
*out_len = need; /* always report the size needed */
if (out_cap < need) return PLUGIN_TOO_SMALL; /* nothing written */
memcpy(out, in->prefix, plen);
for (size_t i = 0; i < in_len; ++i) out[plen + i] = (uint8_t)toupper(in_buf[i]);
return PLUGIN_OK;
}
static void p_destroy(void *inst) {
struct instance *in = inst;
if (!in) return;
host_api h = in->host; /* copy before freeing the owner of the pointers */
h.log(h.host_ctx, "plugin: destroyed");
h.free_mem(h.host_ctx, in->prefix);
h.free_mem(h.host_ctx, in);
}
static const plugin_api api = { sizeof(plugin_api), PLUGIN_ABI_VERSION, p_create, p_process, p_destroy };
const plugin_api *plugin_get_api(uint32_t v) { return v == PLUGIN_ABI_VERSION ? &api : NULL; }
#include "plugin_api.h"
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static size_t live_allocs;
static void *h_alloc(void *ctx, size_t n) { (void)ctx; live_allocs++; return malloc(n); }
static void h_free(void *ctx, void *p) { (void)ctx; if (p) live_allocs--; free(p); }
static void h_log(void *ctx, const char *m) { printf("[host log:%s] %s\n", (const char *)ctx, m); }
int main(int argc, char **argv) {
const char *path = argc > 1 ? argv[1] : "./plugin.so";
void *lib = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!lib) { fprintf(stderr, "dlopen: %s\n", dlerror()); return 1; }
const plugin_api *(*get)(uint32_t) = (const plugin_api *(*)(uint32_t))dlsym(lib, "plugin_get_api");
if (!get) return 1;
printf("ABI 99 request -> %s\n", get(99) ? "accepted" : "refused (NULL)");
const plugin_api *api = get(PLUGIN_ABI_VERSION);
if (!api || api->size < sizeof(plugin_api)) return 1;
host_api host = { sizeof host, h_alloc, h_free, h_log, "main" };
void *inst = api->create(&host, ">> ");
if (!inst) return 1;
uint8_t small[4], big[64];
size_t need = 0;
int rc = api->process(inst, (const uint8_t *)"hello", 5, small, sizeof small, &need);
printf("small buffer: rc=%d, need=%zu\n", rc, need);
rc = api->process(inst, (const uint8_t *)"hello", 5, big, sizeof big, &need);
printf("big buffer: rc=%d, out=\"%.*s\"\n", rc, (int)need, big);
api->destroy(inst); /* instance first ... */
inst = NULL;
dlclose(lib); /* ... library last: api and callbacks' code are gone after this */
printf("allocations still live after destroy: %zu\n", live_allocs);
return 0;
}
Built and run in a Linux container (GCC 14.4, aarch64) with the plugin as a shared library and both sides under ASan (AddressSanitizer, which traps invalid memory accesses and frees) and UBSan (UndefinedBehaviorSanitizer, which traps operations the C standard leaves undefined): gcc -O1 -g -Wall -Wextra -fPIC -shared -fsanitize=address,undefined plugin.c -o plugin.so && gcc -O1 -g -Wall -Wextra -fsanitize=address,undefined host.c -o host -ldl && ./host ./plugin.so:
ABI 99 request -> refused (NULL)
[host log:main] plugin: created
small buffer: rc=-2, need=8
big buffer: rc=0, out=">> HELLO"
[host log:main] plugin: destroyed
allocations still live after destroy: 0
Reading the output line by line: the ABI 99 line shows that asking for an unsupported version yields NULL instead of a misread table. The created and destroyed log lines show the host's callback working in both directions across the boundary. small buffer: rc=-2, need=8 shows that a 4-byte output buffer was refused with nothing written, and that the plugin reported the 8 bytes it needs (the 3-byte prefix >> plus 5 input bytes). big buffer shows the retry succeeding with >> HELLO. The host's allocation counter returning to zero shows every block the plugin obtained through the host was returned through the host, and ASan and LeakSanitizer (the leak checker that runs with ASan) stayed silent. To confirm the "unload last" rule is real, swap the order in a copy of the host (dlclose before destroy) and run it: the process dies with a segmentation fault (exit status 139 without sanitizers; under ASan the report is SEGV and the exit status is 1), because destroy points into the unmapped library.
Trade-offs and what flips the design
Isolation decides whether this contract is enough at all; the other points refine it.
- Version evolution. Appending fields to
plugin_apiandhost_apikeeps old plugins working, because each side checkssizebefore touching a new field. If you need to break the layout, bumpPLUGIN_ABI_VERSION. - Isolation. In-process plugins share the host's address space, so a buggy or hostile plugin can corrupt the host or leak secrets; the contract only prevents honest mistakes. If plugins are not trusted, put them in a separate process with a message protocol (and shared memory only for bulk data), accepting the copy and latency cost.
- Zero-copy. If large buffers make the copy in
processtoo expensive, add a borrowed-view variant with an explicit lifetime rule ("valid until the next call on this instance") instead of transferring ownership. - Thread safety and re-entrancy. Callbacks invoked from plugin-created threads need a documented threading rule, and the host must not destroy an instance while a callback is running.
- Testing the contract. Run a conformance harness against every plugin under ASan and LeakSanitizer with the counting allocator above; fail the plugin if the live count is not zero or if it calls anything outside the table.
Compare C-style manual resource cleanup with RAII in C++. In a codebase where exceptions are disabled, what idiomatic patterns manage resources deterministically, and what would a small RAII wrapper look like?
Sample Answer
Direct answer
C-style cleanup is manual: acquire resources, and on every exit path (success, each early return, each error) release exactly the ones already acquired, usually by jumping to one goto out; label at the end. RAII (resource acquisition is initialisation) ties each resource's release to an object's destructor. A destructor is a function the language calls automatically when an object's lifetime ends, and for a local variable that happens when it leaves its scope (the { } block it was declared in). So the release runs on every path, in reverse order of construction. Turning exceptions off (-fno-exceptions) removes only exception unwinding, which is the compiler-generated cleanup that runs destructors while an exception travels up the call stack; destructors still run on return, break, goto and falling off the end of a scope, so RAII keeps working. What exceptions-off changes is how failure is reported: constructors cannot throw, so you use a factory (a static function that builds and returns the object) that returns an empty or failed object, check it, and keep destructors that cannot fail. The small wrapper below is a move-only owner of a FILE* (move-only means it cannot be copied, only handed over, so there is never a second owner), plus std::unique_ptr with a custom deleter (a small function object telling the pointer how to release this kind of resource) for a malloc buffer.
Structured comparison
C: single-exit goto | C++: RAII objects | |
|---|---|---|
| Who releases | the programmer, at the label | the destructor, by the language |
New early return added later | easy to forget cleanup (leak) | still correct, nothing to update |
| Order | you write reverse order by hand | automatic reverse of construction |
| Ownership transfer | a convention in comments | a move-only type or unique_ptr, enforced by the compiler |
| Partial acquisition | NULL-initialise everything, free what is non-null | an object that failed to acquire is empty, its destructor does nothing |
Patterns that work without exceptions
Patterns 1 to 3 cover most code; 4 to 6 handle particular situations.
- Scope-owned wrapper per resource (the
Fileclass below): constructor or factory acquires, destructor releases, copying is deleted, moving transfers ownership. std::unique_ptr<T, Deleter>for any C handle: a deleter functor callsfree,fclose,close,munmap.- Fallible construction through a factory (fallible: it can fail):
static File open(path, mode)returns an object that is empty on failure; the caller tests it (if (!f) ...). No constructor ever needs to fail. - Explicit status where close can fail: a destructor cannot report an error, so give the class a
close()that returns thefclosestatus for code that cares (writes to disk), and let the destructor be the safety net. The second example below shows it. - Scope guard (a tiny object running a lambda, i.e. a small inline function, in its destructor) for one-off cleanups that do not deserve a class; the second example below shows one. Arenas and pools (one object that owns many allocations and releases them all in one place) fit when many small objects share a lifetime.
- Allocation failure: use the
std::nothrowform ofnew(the version that returns a null pointer instead of throwing) ormalloc, and test the result, since there is no handler to throw to. A function markednoexceptpromises not to throw, which is what the move operations below declare.
Worked example
Compiled with g++ -std=c++17 -O2 -fno-exceptions -Wall -Wextra -fsanitize=address,undefined raii.cpp (GCC 14, Linux; run in a container). The C-style function is compiled as C++ here only so both styles share one file; in a C project it is plain C.
// build: g++ -std=c++17 -fno-exceptions -Wall -Wextra raii.cpp
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <utility>
// 1. C-style: one exit label, cleanup in reverse order of acquisition
int process_c(const char* path) {
int rc = -1;
FILE* f = nullptr;
char* buf = nullptr;
f = std::fopen(path, "r");
if (!f) goto out;
buf = static_cast<char*>(std::malloc(64));
if (!buf) goto out;
if (!std::fgets(buf, 64, f)) goto out;
rc = 0;
out:
std::free(buf); // free(NULL) is a no-op
if (f) std::fclose(f);
return rc;
}
// 2. Small RAII wrapper: owns one FILE*, move-only, no exceptions
class File {
public:
File() = default;
static File open(const char* path, const char* mode) { File f; f.fp_ = std::fopen(path, mode); return f; }
File(const File&) = delete;
File& operator=(const File&) = delete;
File(File&& o) noexcept : fp_(std::exchange(o.fp_, nullptr)) {}
File& operator=(File&& o) noexcept { if (this != &o) { reset(); fp_ = std::exchange(o.fp_, nullptr); } return *this; }
~File() { reset(); }
explicit operator bool() const { return fp_ != nullptr; }
FILE* get() const { return fp_; }
private:
void reset() { if (fp_) { std::fclose(fp_); std::puts(" (File closed)"); fp_ = nullptr; } }
FILE* fp_ = nullptr;
};
// 3. unique_ptr with custom deleter for a C handle
struct FreeDeleter { void operator()(void* p) const { std::free(p); std::puts(" (buffer freed)"); } };
using CBuf = std::unique_ptr<char, FreeDeleter>;
int process_cpp(const char* path) {
File f = File::open(path, "r");
if (!f) return -1; // nothing to clean by hand
CBuf buf(static_cast<char*>(std::malloc(64)));
if (!buf) return -1;
if (!std::fgets(buf.get(), 64, f.get())) return -1; // early return: both destructors still run
std::printf(" read: %s", buf.get());
return 0;
}
int main() {
std::FILE* t = std::fopen("sample.txt", "w"); std::fputs("hello\n", t); std::fclose(t);
std::printf("C style rc=%d\n", process_c("sample.txt"));
std::printf("RAII rc=%d\n", process_cpp("sample.txt"));
std::printf("RAII missing file rc=%d\n", process_cpp("nope.txt"));
}
C style rc=0
read: hello
(buffer freed)
(File closed)
RAII rc=0
RAII missing file rc=-1
Reading it: in process_cpp, f was constructed before buf, and the output shows (buffer freed) before (File closed), so destruction ran in reverse order of construction with no code written for it. In the missing-file call the function returned before buf existed; the empty File destructor printed nothing, because it had nothing to close. No leak report appeared from the sanitizer run. The goto out version works too, but each new resource and each new early exit is a place to make a mistake.
The non-obvious lines of File:
std::exchange(o.fp_, nullptr)storesnullptrino.fp_and returns the old value (cppreference: "Replaces the value ofobjwithnew_valueand returns the old value ofobj"). In the move constructor it takes the handle and leaves the source empty, so only one object will ever close it.File(File&& o) noexceptis the move constructor;noexceptpromises it never throws, which it cannot, since it only copies a pointer.reset()closes the file if there is one and sets the pointer to null, so calling it twice is harmless. The destructor and the move assignment both use it.explicit operator bool()letsif (!f)ask "did the open succeed?";explicitstops aFilefrom silently converting to a number elsewhere.
Scope guard and a checked close
The same approach applies to a one-off cleanup and to a close that can fail. Built the same way as above (g++ -std=c++17 -O2 -fno-exceptions -Wall -Wextra -fsanitize=address,undefined, GCC 14, Linux):
#include <cstdio>
#include <utility>
// Runs a callable when the object leaves scope.
template <class F>
class ScopeGuard {
public:
explicit ScopeGuard(F f) : f_(std::move(f)) {}
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
~ScopeGuard() { f_(); }
private:
F f_;
};
// A file wrapper whose close() reports the fclose result.
class OutFile {
public:
OutFile() = default;
OutFile(const OutFile&) = delete;
OutFile& operator=(const OutFile&) = delete;
OutFile(OutFile&& o) noexcept : fp_(std::exchange(o.fp_, nullptr)) {}
static OutFile open(const char* path) { OutFile f; f.fp_ = std::fopen(path, "w"); return f; }
explicit operator bool() const { return fp_ != nullptr; }
std::FILE* get() const { return fp_; }
int close() { // 0 on success, EOF on failure; safe to call twice
if (!fp_) return 0;
int rc = std::fclose(fp_);
fp_ = nullptr;
return rc;
}
~OutFile() { close(); } // safety net: result ignored here
private:
std::FILE* fp_ = nullptr;
};
int save(const char* path) {
OutFile out = OutFile::open(path);
if (!out) return -1;
ScopeGuard log([] { std::puts(" (save() finished)"); });
std::fputs("data\n", out.get());
return out.close() == 0 ? 0 : -2; // the caller learns whether the flush worked
}
int main() {
std::printf("save rc=%d\n", save("out.txt"));
std::printf("save to missing dir rc=%d\n", save("no_such_dir/out.txt"));
}
(save() finished)
save rc=0
save to missing dir rc=-1
The guard's lambda ran when save returned, without any cleanup call in the body. The checked close() returns the fclose result, so a failed flush becomes the return code -2 instead of being lost. The missing directory made open fail, and the early return -1 ran no guard because it had not been constructed yet.
Pitfalls
- Copying a handle wrapper would double-close the same
FILE*; that is why copy is= deleteand move usesstd::exchangeto null the source. - A destructor that does real work and can fail has nowhere to report it with exceptions off; keep it to the release call and expose
close()for checked shutdown. - Skipped destructors: RAII does not run on
exit()called mid-function,abort(),_exit()or a crash, andlongjmp(the C function that jumps straight back to an earlier saved point, abandoning the frames in between) over C++ frames is undefined behaviour if it skips non-trivial destructors (destructors that do real work). Return error codes up the stack instead. - Two-phase initialisation (default-construct then
init()) recreates the C problem of half-built objects; the factory approach avoids it. - Mixing styles: when a C API requires a callback with a raw pointer, keep the owner object alive in the caller's scope and pass
.get().
Judgement
In a codebase with exceptions disabled, commit to RAII wrappers with factory-style construction and explicit status codes; keep the goto cleanup idiom only in actual C files or in a C library you must match. If a resource is used once in a tiny function, a goto is fine; as soon as there are two resources or more than one exit, wrap them.
Unlock Full Question Bank
Get access to all 44 Language-Level Memory Management (C/C++/Rust) interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.