The Complete Guide to Memory Safety in C and C++
A map of memory-safety bugs in C and C++, from stack overflows to use-after-free and type confusion, with the habits, tools and flags that stop each one.

Most serious vulnerabilities in C and C++ programs are memory-safety bugs. A program reads or writes memory it was never given, or uses memory after it was taken back, or treats bytes as something they are not. The language does not stop it. It does not even promise that the program will crash. The standard says the behavior is undefined, which in practice means the compiler may assume the bug does not exist and generate code that does anything at all, including code that works in testing and fails in production. This guide is the map for the whole subject. It names each class of bug, shows what each one looks like in code, explains how a bug becomes an exploit, and then goes through the defenses in the order you can adopt them: habits in the code, warnings in the compiler, sanitizers in testing, mitigations in the binary and hardware in the CPU. Each section points to a deeper post in this series. Examples target GCC 15 and Clang 20 on x86-64 Linux 6.12 with glibc 2.41, in C17 and C++23.
What memory safety means
A program is memory safe if every memory access it performs is to an object that is alive, within that object's bounds and of the type the program believes it has. Break any of the three and the program is unsafe. The properties have names:
| Property | Question it answers | Violation |
|---|---|---|
| Spatial safety | Is the access inside the object? | buffer overflow, out-of-bounds read |
| Temporal safety | Is the object still alive? | use-after-free, double free, dangling stack pointer |
| Type safety | Is the object of the type the access assumes? | type confusion, bad cast, union misread |
| Initialization | Has the object been given a value? | uninitialized read |
| Thread safety | Could another thread change it meanwhile? | data race |
Languages such as Java, Go, Python and safe Rust enforce most of these for you. C and C++ do not, and they cannot without changing what they are: a C pointer is an address, a C array has no length once it becomes a pointer and free is a function like any other. The upside is control and speed. The cost is that correctness of every access is the programmer's job, in every line, forever.
Three facts frame the rest of the guide.
Memory bugs are common, even in careful code. Large projects maintained by skilled teams, with code review and testing, keep finding them. A defense that relies on never making a mistake will fail.
Memory bugs are exploitable. An attacker who controls the data that triggers the bug can often turn an out-of-bounds write into code execution, an out-of-bounds read into a leaked secret or a use-after-free into a hijacked function pointer.
No single tool finds them all. Compilers find some, sanitizers find others, fuzzers find still others and reviews find the rest. The goal is layers.
How undefined behavior works
The C and C++ standards define a set of operations whose behavior is undefined: writing past the end of an array, dereferencing a null pointer, signed integer overflow, using an object after its lifetime ends, reading an uninitialized automatic variable in most cases. For these, the standard places no requirements on the implementation. The compiler is allowed to assume they never happen and to optimize on that assumption.
That has a consequence people find surprising. A check written after the undefined operation may be removed, because the compiler concludes that the check can only matter if the operation misbehaved, which it may assume it did not:
#include <stdio.h>
static int checked_get(const int *p)
{
int v = *p; /* dereference first */
if (p == NULL) /* compiler may delete this test */
return -1;
return v;
}
int main(void)
{
int x = 7;
printf("%d\n", checked_get(&x));
return 0;
}7For a valid pointer the program is fine. The danger is the null case: because *p came first, the compiler may treat p == NULL as impossible and drop the branch, so a null argument crashes at the dereference instead of returning -1. The test did what it looked like it did only in a program that never needed it. Undefined behavior is a property of the program as a whole and not of the line that executes, which is why you cannot reason about it by running the code and watching.
The practical rule is to treat every undefined operation as a defect, whether or not you have seen it fail.
Spatial bugs: going out of bounds
Stack buffer overflows
The classic case is a copy into a local array without a size check. The bytes beyond the array overwrite neighboring locals, the saved frame pointer and the return address. The post on stack buffer overflows walks through the layout. In short:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
char name[8];
if (argc < 2)
return 1;
strcpy(name, argv[1]); /* no length limit */
printf("hello %s\n", name);
return 0;
}Given a long argument, strcpy writes beyond name. The same program with snprintf(name, sizeof name, "%s", argv[1]) and a check of its return value cannot. Replace strcpy, strcat, sprintf and gets with bounded forms, which the post on safer alternatives to strcpy and sprintf covers one function at a time.
Heap buffer overflows
The same mistake with malloc memory damages the next chunk or the allocator's own bookkeeping, and the program usually crashes later, in an unrelated free. The post on heap buffer overflows shows what AddressSanitizer reports and how a size computed from untrusted input becomes a short allocation.
Off-by-one errors
A string of five characters needs six bytes. A loop with <= instead of < visits one element too many. A strncpy that fills the destination leaves no terminator. One byte is enough to clear the low byte of a neighboring pointer, and the post on off-by-one errors in C strings lists the patterns and the habits that avoid them.
Integer overflow feeding a size
Many overflows are caused by arithmetic one step earlier. If count * size wraps, malloc returns a block that is far too small and the loop that fills it runs for count iterations. Unsigned arithmetic wraps by definition, and signed overflow is undefined, so a check like a + 1 < a can vanish at -O2. Use calloc, reallocarray or the checked builtins, which the posts on integer overflow and on ckd_add and __builtin_add_overflow describe.
Format strings
printf(user_text) hands attacker input to a mini-language that reads from the stack and, with %n, writes to memory. It is a spatial bug of an unusual kind: the out-of-bounds access is performed by the library on the attacker's behalf. The fix is printf("%s", user_text), and the compiler can find the mistake with -Wformat-security, as the post on format string vulnerabilities explains.
Out-of-bounds reads
Reads are quieter than writes. A read past the end of a buffer does not corrupt anything and may leak the next object's contents, such as keys, pointers or earlier requests. The most famous example is a bug where a program trusted a length field supplied by the peer and echoed back that many bytes. Reads also defeat ASLR by revealing addresses. Treat every length that crosses a trust boundary as hostile.
Temporal bugs: using memory at the wrong time
Use-after-free
A pointer outlives the object. After free(p), the block belongs to the allocator, which may hand it to the next caller. The stale pointer now aliases a different object, so reads see someone else's data and writes corrupt it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char *a = malloc(16);
strcpy(a, "guest");
free(a);
char *b = malloc(16); /* often the same block */
strcpy(b, "root");
printf("%s\n", a); /* stale pointer */
free(b);
return 0;
}rootThe output is not guaranteed, which is the point. On glibc, the freed 16-byte request goes to the thread's tcache and comes straight back for b, so the stale a shows what b wrote. The post on use-after-free bugs covers the shapes this takes in real code, such as two owners, a loop that reads next after freeing a node, a callback that fires after its object was destroyed and an iterator that survives a std::vector reallocation.
Double free
Freeing the same block twice can put it on the allocator's list twice, after which two later allocations return the same memory. glibc detects many double frees and prints free(): double free detected in tcache 2, and detection is best effort. The post on double free bugs explains how the check works and why a single cleanup block with pointers initialized to NULL removes most of them.
Dangling stack pointers
Returning the address of a local variable, or storing it somewhere that outlives the function, is the stack version. GCC warns about the direct case with -Wreturn-local-addr, and AddressSanitizer reports the rest with ASAN_OPTIONS=detect_stack_use_after_return=1. In C++ the same bug hides in std::string_view, std::span and references to temporaries, which look safe because they are library types.
Iterator and reference invalidation
C++ containers promise stability only under rules. A std::vector that grows may move its elements, and every pointer, reference and iterator into it becomes invalid. The code below compiles and is undefined:
#include <cstdio>
#include <vector>
int main()
{
std::vector<int> v{1, 2, 3};
int &first = v[0];
v.push_back(4); /* may reallocate */
std::printf("%d\n", first); /* dangling reference */
return 0;
}With AddressSanitizer enabled, the read is reported as heap-use-after-free, and it names the push_back that freed the old buffer. Without it, the program usually prints 1, because the freed block still holds the old value until something reuses it. The rule is simple and easy to forget: after any operation that can change a container's size, discard the pointers you took from it.
Type and initialization bugs
Uninitialized memory
A local that is declared and not set holds whatever was on the stack. Reading it leaks old data or makes a branch depend on it, and returning a struct with padding or unset fields copies the garbage to a peer. -Wuninitialized finds the simple cases. Clang and GCC can also zero or pattern-fill every automatic variable with -ftrivial-auto-var-init, as the post on uninitialized memory explains, and calloc or memset handle the heap.
Type confusion
Treating an object as a type it is not, usually through a static_cast downcast that was wrong, a reinterpret_cast, a union read of the wrong member or a tagged record whose tag and payload disagree. Field accesses then use the wrong offsets, and an attacker who controls the confused field controls a pointer. The post on type confusion in C++ shows how -fsanitize=vptr and Clang CFI catch downcast errors.
Data races
Two threads accessing the same memory with at least one writer and no synchronization is a data race, and in C11 and C++11 it is undefined behavior. The memory-safety consequence is that a race on a pointer or a length can produce a torn value, and a race between a free and a use is a use-after-free that happens only under load. ThreadSanitizer finds data races at run time. Prevention is structural: share by passing ownership, protect shared state with a mutex or an atomic and avoid sharing mutable state when you can.
From bug to exploit
Knowing how an attacker uses a bug explains why the defenses look the way they do. The sequence is similar across bug classes.
Trigger. The attacker supplies input that reaches the bug: a long string, a crafted length, a specific order of requests.
Primitive. The bug gives them a capability. An overflow of a stack buffer yields a controlled write to a range of addresses. A use-after-free yields a stale pointer to an object they can reallocate. A format string yields an arbitrary read and write.
Leak. With ASLR on, they need an address first. A read primitive, a format string or a stray pointer in an error message supplies it.
Control. They overwrite something that decides what code runs next: a return address, a function pointer, a vtable pointer, an entry in the global offset table.
Payload. With NX on, they cannot run injected bytes. They chain pieces of existing code, called gadgets, or call library functions with chosen arguments, a technique called return-oriented programming.
Each mitigation in the binary breaks one step. Stack canaries make the control overwrite fail on the stack. NX makes injected payloads useless. ASLR forces the leak. Full RELRO makes the global offset table read-only. Position-independent executables extend ASLR to the program's own code. Control-flow integrity and shadow stacks restrict where a hijacked jump can go. None of them removes the bug, which is why the first line of defense is still writing code without it.
Defense 1: write code that cannot go wrong
The cheapest fix is a habit that removes a whole class.
Carry the length with the pointer
A char * that points to a buffer is not enough. Pass (ptr, len) together, or wrap them in a struct, and check the length at every access. In C++, std::span<T> is exactly this pair, and std::string_view is the same for read-only text, with the lifetime caveat above. std::array and std::vector know their sizes. Use at() when you want a checked access, and see the section on hardened libraries below to get checking from operator[].
Use bounded library calls and check the result
Prefer snprintf to sprintf, fgets to gets, %7s to %s in scanf, memcpy after an explicit length check to a loop. Check the return value of snprintf against the buffer size to detect truncation, and decide deliberately whether truncation is an error.
Compute sizes safely
Use calloc(n, size) or reallocarray(ptr, n, size) for arrays. For other arithmetic, ckd_add, ckd_sub and ckd_mul from C23's <stdckdint.h>, or the GNU __builtin_*_overflow family, give an overflow flag without undefined behavior. Keep sizes in size_t, and be suspicious of any conversion between signed and unsigned types.
Give every allocation one owner
Decide who frees each block, write it down, and let everything else borrow. In C, name the functions that transfer ownership and the ones that do not. Set a pointer to NULL after freeing it, which turns a double free into a harmless call and a later dereference into an immediate crash. Use a single cleanup path with pointers initialized to NULL at the top of the function.
Use RAII in C++
Resource acquisition is initialization means a resource's lifetime is tied to a scope. std::unique_ptr<T> owns one object and frees it exactly once. std::shared_ptr<T> counts owners. Containers and std::string release their memory in destructors. A raw new or delete in application code is a signal to stop and ask whether a smart pointer or a container fits. The C++ Core Guidelines, maintained by Bjarne Stroustrup and Herb Sutter, have a long section on resource management that is worth reading in full.
Initialize everything
Declare variables where they are first assigned, give them a value at the declaration and zero a struct before it crosses a trust boundary. struct reply r = {0}; costs nothing and removes the leak.
Avoid what you cannot check
Variable-length arrays and alloca with attacker-influenced sizes enable stack clash attacks, and the Linux kernel removed its VLAs for that reason. Raw pointer arithmetic, reinterpret_cast, unions used for type punning and C-style casts each skip a check. When you need one, isolate it in a small function with a comment stating the invariant.
Defense 2: let the compiler help
Compilers know the sizes of arrays and the types of arguments, and they report mistakes if you ask. A starting set of flags:
gcc -std=c17 -O2 -Wall -Wextra -Wformat=2 -Wvla -Wconversion \
-Werror=format-security -Werror=implicit-function-declarationSeveral of the most useful warnings, -Wstringop-overflow, -Warray-bounds and -Wnull-dereference, depend on the optimizer, so they need -O2 to fire. The post on compiler warnings for security bugs gives the list with the bug each finds and a plan for turning them on in a large existing project. GCC's -fanalyzer follows paths through a function and reports use-after-free, double free and leaks in C, with an explanation of the path.
Mark your printf-style wrappers with __attribute__((format(printf, ...))), so the compiler checks their callers. The post on writing safe printf-style wrappers shows both the ... and va_list forms.
Defense 3: sanitizers and tools in testing
Sanitizers insert checks into your program at compile time and report violations with a line number, the allocation site and the free site.
| Tool | Flag | Finds |
|---|---|---|
| AddressSanitizer | -fsanitize=address | heap, stack and global overflows, use-after-free, double free, leaks |
| UndefinedBehaviorSanitizer | -fsanitize=undefined | signed overflow, bad shifts, misaligned access, null dereference, bad downcasts with vptr |
| MemorySanitizer (Clang) | -fsanitize=memory | reads of uninitialized memory |
| ThreadSanitizer | -fsanitize=thread | data races |
| Valgrind Memcheck | no recompile | invalid reads and writes, use of uninitialized values, leaks |
A realistic test setup builds the test suite once with ASan and UBSan and runs it in CI, builds once with TSan for the concurrent code and runs a fuzzer on every parser with ASan on. Sanitizers cost memory and time, so they live in test builds. AddressSanitizer and Valgrind cannot run together, and ASan and TSan cannot be combined in one binary.
Fuzzing complements them. A fuzzer such as libFuzzer or AFL++ generates inputs, watches coverage and keeps the ones that reach new code. Pointed at a parser and compiled with sanitizers, it finds inputs that trigger overflows that no hand-written test would try. Every parser of untrusted data should have a fuzz target.
Run unit tests with the boundary values for every buffer: length zero, size - 1, size and size + 1. These four inputs expose most off-by-one bugs.
Defense 4: mitigations in the binary
Mitigations assume a bug exists and make exploiting it harder. They are cheap, they are mostly compiler and linker flags and a few of them are on by default in distribution toolchains. Turn them on explicitly so the result does not depend on the toolchain.
| Mitigation | Flag | What it stops |
|---|---|---|
| Stack protector | -fstack-protector-strong | return-address overwrites from stack overflows |
| Fortified libc | -O2 -D_FORTIFY_SOURCE=3 | overflows in memcpy, strcpy, sprintf when sizes are known |
| PIE | -fPIE -pie | fixed addresses for the program's code |
| Full RELRO | -Wl,-z,relro,-z,now | overwrite of the global offset table |
| Non-executable stack | -Wl,-z,noexecstack | injected code on the stack |
| Stack clash protection | -fstack-clash-protection | jumping over the guard gap |
| Control-flow markers | -fcf-protection=full | jumps into the middle of functions, return hijacking with shadow stacks |
| Zero-init of locals | -ftrivial-auto-var-init=zero | leaks from uninitialized locals |
Each has a post in this series, and the guide to exploit mitigations on Linux and the guide to compiler and linker hardening flags cover them together. Verify the result in the binary, because a flag that never reached the compiler protects nothing. The checksec tool and a handful of readelf commands report the properties of a built executable.
Kernel mitigations, such as KASLR, SMEP, SMAP and KPTI, protect the operating system from the same bug classes. User-space programs benefit from them without doing anything.
Defense 5: hardened libraries and allocators
Standard libraries can check what the language does not. In C++, libc++ has hardening modes selected with _LIBCPP_HARDENING_MODE, and libstdc++ has _GLIBCXX_ASSERTIONS. Either makes vector::operator[], span::operator[] and optional::operator* check their preconditions and terminate on a violation, with no source changes. The post on bounds-checked containers and hardened libc++ shows the macros and the failure output.
Allocators can raise the cost of heap exploitation and catch misuse. Scudo and hardened_malloc put metadata out of line, add guard pages and delay reuse of freed memory, and GWP-ASan samples a fraction of allocations onto guarded pages to give exact reports from deployed programs. They are described in the post on hardened allocators. Neither fixes a bug, and both turn some silent corruption into a clear crash.
Defense 6: hardware
Newer CPUs implement memory-safety checks in silicon. Arm's Memory Tagging Extension tags allocations and pointers with four bits and faults on a mismatch, so a heap overflow or a use-after-free is caught with high probability at low cost. Intel CET adds a shadow stack for return addresses and branch-target markers, and Arm has pointer authentication and branch target identification. These features appear in the later posts of this subcluster. The shared pattern is that the compiler and the operating system do the work and your code is unchanged, provided every object in the program is built to match.
Defense 7: a safer language where it counts
Rust enforces ownership and borrowing at compile time, bounds-checks indexing and rejects uninitialized reads, which removes spatial, temporal and initialization bugs from safe code. The post on how Rust prevents memory-safety bugs shows the compiler errors. A full rewrite is rarely the right first step. A practical path is to write new code that parses untrusted input in a memory-safe language, call it from C through a narrow interface and keep that interface small and well tested.
Inside C++, modern practice narrows the unsafe surface: std::span instead of pointer and length, std::unique_ptr instead of new, std::variant instead of unions and hardened libraries instead of unchecked indexing.
Objects, lifetimes and pointers in the C memory model
Many of the bugs above are easier to see once you hold the C model of memory in your head. An object is a region of storage with a type, and every object has a storage duration that decides when it is alive. Static objects, such as globals and static locals, live for the whole program. Automatic objects, the ordinary locals, live until the block that declares them ends. Allocated objects, from malloc and its relatives, live until free. Thread-local objects live as long as their thread. A pointer is valid only while the object it points to is alive, and a pointer one past the end of an array is valid to form and invalid to dereference.
Three consequences surprise people who learned C by experimenting.
A pointer is not just an address. The standard ties a pointer to the object it was derived from, and the compiler is allowed to assume that a pointer derived from one object does not access another. Computing an address by integer arithmetic and converting it back, or walking from the end of one array into the start of the next, may work on your machine and is not defined. This assumption is called provenance, and it is the reason a loop over a pointer that wanders out of its array can be compiled into something that never matches what you wrote.
Comparison and arithmetic are only defined inside an object. Subtracting two pointers into different arrays, or comparing them with <, is undefined, and so is forming a pointer more than one element past the end. Code that checks if (p + len > end) can overflow the pointer arithmetic itself when len is huge, and the compiler may then delete the check. The safe form compares lengths and not addresses: if (len > (size_t)(end - p)).
Alignment and aliasing matter. Reading a uint32_t from a char buffer through a cast pointer violates the strict aliasing rules and, on some CPUs, alignment requirements. The portable way to reinterpret bytes is memcpy into an object of the target type, which compilers turn into a single load where the hardware allows.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static uint32_t read_u32_le(const unsigned char *p)
{
uint32_t v;
memcpy(&v, p, sizeof v); /* no aliasing or alignment problem */
return v; /* host is little-endian on x86-64 */
}
int main(void)
{
unsigned char wire[] = { 0x78, 0x56, 0x34, 0x12 };
printf("0x%08x\n", read_u32_le(wire));
return 0;
}0x12345678On a big-endian host the same code would print 0x78563412, so a protocol parser should assemble the value from bytes with shifts and not rely on host order. The point of the example is the memory model: the memcpy form is defined everywhere, and the cast *(const uint32_t *)p is not.
A catalog of safe patterns in C
C has no built-in slice type, and a handful of small patterns give you most of what one would.
A slice: pointer and length together
#include <stddef.h>
#include <stdio.h>
struct bytes {
const unsigned char *ptr;
size_t len;
};
static inline int bytes_get(struct bytes b, size_t i, unsigned char *out)
{
if (i >= b.len)
return -1; /* out of range, caller must check */
*out = b.ptr[i];
return 0;
}
static inline struct bytes bytes_sub(struct bytes b, size_t off, size_t n)
{
struct bytes empty = { NULL, 0 };
if (off > b.len || n > b.len - off) /* no overflow in the comparison */
return empty;
struct bytes s = { b.ptr + off, n };
return s;
}The subtraction b.len - off is safe because the first test has already established off <= b.len, and testing n > b.len - off avoids the overflow that off + n > b.len could suffer. Every parser in the program reads through these two functions, so there is exactly one place to get the bounds check right and one place to fuzz.
A parser cursor that cannot overrun
A parser that walks a buffer is the most common place for spatial bugs. A cursor with a remaining length makes every read explicit:
#include <stdint.h>
#include <stdio.h>
#include <string.h>
struct cursor {
const unsigned char *p;
size_t left;
};
static int take_u16(struct cursor *c, uint16_t *out)
{
if (c->left < 2)
return -1;
*out = (uint16_t)(c->p[0] | (c->p[1] << 8));
c->p += 2;
c->left -= 2;
return 0;
}
static int take_bytes(struct cursor *c, void *dst, size_t n)
{
if (c->left < n)
return -1;
memcpy(dst, c->p, n);
c->p += n;
c->left -= n;
return 0;
}
int main(void)
{
const unsigned char msg[] = { 0x03, 0x00, 'a', 'b', 'c' };
struct cursor c = { msg, sizeof msg };
uint16_t len;
char text[8];
if (take_u16(&c, &len) != 0 || len >= sizeof text ||
take_bytes(&c, text, len) != 0) {
puts("bad message");
return 1;
}
text[len] = '\0';
printf("len=%u text=%s\n", (unsigned)len, text);
return 0;
}len=3 text=abcThe length field comes from the message, so the code checks it against the destination (len >= sizeof text) and against what remains in the input (c->left < n) before copying. An attacker who sets the length to 60000 gets bad message. This is the same fix that prevents the whole family of bugs where a parser trusts a length and reads or writes past a buffer.
An arena for grouped lifetimes
When many objects share one lifetime, such as everything allocated while handling one request, allocate them from an arena and release the arena once. Individual free calls vanish, and with them the double free and the early free of an object that is still referenced. The arena itself must check that an allocation fits and that the size computation does not overflow, using the checked arithmetic from the earlier section.
Ownership in names
When a function takes ownership of a pointer, say so in its name or its comment, and keep the convention across the codebase. A prefix such as take_ for functions that consume an argument and borrow_ or a const pointer for functions that do not is enough. The point is that a reader can tell at the call site whether the caller still owns the object, which is the question that double-free and use-after-free bugs answer wrongly.
Reading sanitizer reports
A sanitizer report is the fastest route from a crash to a cause, and it follows a fixed layout. AddressSanitizer begins with the kind of error and the address, then gives the access, then the stack of the access, then where the memory came from.
==2417==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000000014 at pc 0x55d7a0b2c1f6 bp 0x7ffc5b6a1ed0 sp 0x7ffc5b6a1ec0
WRITE of size 1 at 0x602000000014 thread T0
#0 0x55d7a0b2c1f5 in fill parser.c:41
#1 0x55d7a0b2c4aa in main parser.c:77
0x602000000014 is located 0 bytes after 4-byte region [0x602000000010,0x602000000014)
allocated by thread T0 here:
#0 0x7fa1d2ee7a57 in malloc
#1 0x55d7a0b2c18a in fill parser.c:36Read it from the middle. The line starting 0x602000000014 is located says how far from the object the access landed: 0 bytes after a 4-byte region means a one-past-the-end write, the signature of an off-by-one or an unchecked loop bound. bytes inside of a freed region would say use-after-free. The first stack tells you which line wrote, and the second tells you which line allocated the object, which is where its size was decided, so the bug is usually in the arithmetic between those two lines. The process id, addresses and offsets change from run to run, and the structure does not.
UndefinedBehaviorSanitizer prints one line per event in the form file:line:column: runtime error: <what happened>, such as signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'. Valgrind prints Invalid write of size 1 with an Address ... is 0 bytes after a block of size 4 alloc'd follow-up that carries the same information.
C++ specifics worth a section
C++ gives you the tools above, and its own hazards deserve a list, since they look safe.
**
std::string_viewandstd::spando not own.** Returning a view of a localstd::string, or storing a view of a temporary, is a use-after-free that no compiler flag treats as an error. Keep views to parameters and short scopes.Lambdas capture by reference.
[&]stored in a callback that outlives the enclosing function captures dangling references. Capture by value for anything that escapes.Range-for over a temporary's member.
for (auto x : make().items())in C++20 and earlier can bind to a destroyed temporary. C++23 fixed some cases of this lifetime extension, so check your standard mode.Moved-from objects. After
std::move(x),xis valid but unspecified. Using its value is a logic error, and using a moved-fromunique_ptrdereferences null.**
operator[]onstd::mapinserts.** It is not a memory bug, and it is a common source of surprising growth.Exceptions and ownership. A raw pointer owned by a function leaks if an exception passes through. Smart pointers and containers prevent it.
Virtual destructors. Deleting a derived object through a base pointer without a virtual destructor runs the wrong destructor, a type-confusion bug with a different name.
Turn on -D_GLIBCXX_ASSERTIONS or the libc++ hardening macro in every C++ build, compile with -Wall -Wextra -Wnon-virtual-dtor -Wdangling-pointer where available and test under AddressSanitizer. The compiler can warn about some of the dangling cases, and the sanitizer reports the rest at the moment of access.
Building a testing strategy around the bug classes
Tests find memory bugs only when they exercise the boundaries, so shape them around the classes. For each function that takes a buffer and a length, write the four boundary cases: zero length, one byte less than capacity, exactly capacity and one byte more. For each parser, add a test per field with the largest legal value, the largest value plus one and the value that makes the next addition overflow. For each allocation function, add a test that frees and reallocates in a loop and a test that fails the allocation on purpose, so the error path runs. Error paths are where double frees live, because they are the code that executes least and is read least.
A second layer is differential and property-based testing. A property such as "the parser never reads past its input" is checked by running it on random and mutated inputs under AddressSanitizer. A fuzzer does this at scale, and a seed corpus built from real captured messages gets it past the first few checks quickly. Keep the crashing inputs the fuzzer finds as regression tests, in the repository, so the fix stays fixed.
A third layer is continuous: run the sanitizer build in CI on every change, run the fuzzers on a schedule for hours rather than seconds and track the number of open sanitizer findings the way you track failing tests. A project that treats a sanitizer report as a failing test fixes bugs when they are one commit old, which is when the cause is obvious.
When memory safety is not only about user space
The same classes of bugs appear in kernels, firmware and drivers, with higher stakes and fewer tools. A kernel module that copies from a user buffer without checking its length has a stack or heap overflow with kernel privileges, which is why the kernel provides copy_from_user and hardened usercopy checks, and why its build system enables stack protection, fortification and variable initialization options. Embedded firmware often runs without an MMU, without ASLR and without a heap, so the mitigations differ, and the habits above matter more: bounded copies, checked arithmetic, no variable-length arrays and static analysis in the build. If your target has a memory protection unit, use it to mark code non-writable and data non-executable, to place a guard region below each task stack and to make a null-pointer access fault.
The posts on kernel hardening and on Arm and Intel hardware features later in this subcluster cover the mitigations that operating systems and CPUs provide. The habits in this guide are the part that you control in every environment.
A workflow for an existing codebase
Turning all of this on at once is unrealistic. An order that works:
Turn on warnings and fix the high-value ones. Start with
-Werror=format-security,-Werror=implicit-function-declarationand-Wformat=2, and add-Wstringop-overflowand-Warray-boundsat-O2.Add the free mitigations.
-fstack-protector-strong,-D_FORTIFY_SOURCE=3with optimization,-fPIE -pie, full RELRO,-z noexecstack. These rarely break anything and add real cost to an attacker.Run the tests under AddressSanitizer and UBSan. Fix every report. Each one is a bug that was waiting.
Replace the worst offenders. Search for
strcpy,strcat,sprintf,getsandscanf("%s"), and formalloc(a * b), and fix each call with the patterns above.Fuzz the parsers. Start with whatever reads files or network data.
Enable hardened containers in C++ code with the library macro.
Add a hardening check to the build. Fail the build if a shipped executable lacks PIE, full RELRO or a non-executable stack.
Deploy a hardened allocator or hardware tagging in services that handle untrusted data.
Move the next parser into a memory-safe language if the project allows it.
Reading list in this series
The posts below go deeper on each topic, roughly from first rung to last: stack buffer overflows, off-by-one errors, replacing strcpy and sprintf, stack canaries, heap overflows, use-after-free, double free, integer overflow, format strings, Rust's guarantees, hardened C++ containers, uninitialized memory and type confusion.
What this guide does not promise
Following it will not make a C or C++ program memory safe in the formal sense. It will remove the bugs that are easy to remove, find many of the rest before release and make the ones that remain harder to exploit and easier to diagnose. The remaining risk lives in code that does pointer arithmetic by hand, in parsers that handle hostile data and in the interfaces between your code and third-party libraries. Treat those as the places to spend review time, fuzzing time and, when the budget allows, a rewrite in a language that checks.


