Safe C Patterns
C will be with us for decades: kernels, firmware, embedded devices, the runtimes of other languages, decades of libraries. Rewriting all of it is neither possible nor always wise, so the practical question is how to write and maintain C that has far fewer memory bugs. The answer isn't heroics but a small set of habits enforced by structure: sizes travel with pointers, arithmetic on sizes is checked, every object has one owner, dangerous functions can't be called at all, and the tools of this course run on every change. The bug-class lessons each ended with a local fix; this lesson collects them into patterns you can adopt for a whole code base. The language itself is in C, with strings and memory management.
Pattern 1: carry the size with the pointer
Most overflows in this course had the same root cause: the code that writes didn't know the capacity. The fix is a type that keeps them together, and functions that refuse to exceed it. A minimal growable byte buffer with checked appends:
#include <stdckdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A length-carrying buffer: data[0..len) is used, data[0..cap) is allocated. */
struct buf { unsigned char *data; size_t len, cap; };
#define BUF_MAX (1u << 20) /* a documented upper bound: 1 MiB */
/* Appends n bytes. Returns 0, or -1 (buffer unchanged) on overflow, limit or out of memory. */
static int buf_append(struct buf *b, const void *src, size_t n) {
size_t need;
if (ckd_add(&need, b->len, n) || need > BUF_MAX) return -1;
if (need > b->cap) {
size_t cap = b->cap ? b->cap : 16;
while (cap < need) cap *= 2; /* cannot overflow: cap <= 2 * BUF_MAX */
unsigned char *p = realloc(b->data, cap);
if (!p) return -1; /* old block still valid and owned by b */
b->data = p; b->cap = cap;
}
memcpy(b->data + b->len, src, n);
b->len = need;
return 0;
}
static void buf_free(struct buf *b) { free(b->data); *b = (struct buf){0}; }
int main(void) {
struct buf b = {0};
printf("append \"hello \": %d\n", buf_append(&b, "hello ", 6));
printf("append \"world\": %d\n", buf_append(&b, "world", 5));
printf("contents: %.*s (len %zu, cap %zu)\n", (int)b.len, (const char *)b.data, b.len, b.cap);
printf("append SIZE_MAX bytes: %d\n", buf_append(&b, "x", (size_t)-1)); /* overflow caught */
printf("append 2 MiB: %d\n", buf_append(&b, "x", 2u << 20)); /* limit caught */
printf("still: len %zu\n", b.len);
buf_free(&b);
buf_free(&b); /* idempotent: safe to call twice */
printf("after free: data %s, len %zu\n", b.data ? "set" : "NULL", b.len);
return 0;
}append "hello ": 0
append "world": 0
contents: hello world (len 11, cap 16)
append SIZE_MAX bytes: -1
append 2 MiB: -1
still: len 11
after free: data NULL, len 0
Every rule from the bug-class lessons is in those 20 lines: the size computation is checked (integer overflow), there is an explicit maximum, realloc failure doesn't lose the old block (leaks), the copy uses the same n that was checked, and buf_free leaves the struct in a state where a second call is harmless (double free). The calls with SIZE_MAX and 2 MiB are rejected before any memory is touched; neither reaches memcpy.
Strings get the same treatment: pass (char *dst, size_t dstsz) pairs, use snprintf and check its return value against the size, fgets instead of gets, and memcpy with lengths you computed and checked. glibc 2.38 and later also provide strlcpy/strlcat (from the BSDs), which always terminate and return the length they tried to create, so truncation can be detected.
Pattern 2: checked arithmetic for every size
Any +, * or - whose operands come from input and whose result becomes a size or an index goes through ckd_add, ckd_mul, ckd_sub (C23, <stdckdint.h>) or __builtin_*_overflow. Allocate arrays with calloc(n, size) or reallocarray(p, n, size), both of which check the multiplication. Keep sizes in size_t, convert input once at the edge with a range check, and never let an error code share a variable with a length (signedness).
Pattern 3: one owner per object, written down
C has no ownership in the type system, so it has to be in names and comments, applied without exceptions:
x_create()/x_destroy()pairs;destroyaccepts NULL and clears what it can.- Functions document whether they borrow a pointer (use it only during the call), take it (now responsible for freeing it) or return a new one (the caller frees it).
- On failure, a function leaves its outputs in a state that is safe to destroy, and transfers ownership only on success.
- Long-lived references go through handles (an index plus a generation number) instead of raw pointers, as in the use-after-free fix.
Pattern 4: make the dangerous functions impossible
Code review forgets; the compiler doesn't. GCC and Clang can refuse to compile any use of a banned identifier:
#include <stdio.h>
#include <string.h>
#pragma GCC poison strcpy strcat sprintf gets
int main(void) {
char dst[8];
strcpy(dst, "lab"); /* any use is now a compile error */
puts(dst);
return 0;
}<source>: In function 'main':
<source>:7:5: error: attempt to use poisoned 'strcpy'
7 | strcpy(dst, "lab"); /* any use is now a compile error */
| ^
<source>:3:20: note: poisoned here
3 | #pragma GCC poison strcpy strcat sprintf gets
| ^~~~~~
The program doesn't build: error: attempt to use poisoned 'strcpy', with a note pointing at the pragma. Put the pragma in a header included everywhere (after the system headers, which may use the names internally) and the list can't erode. Projects such as Git keep a banned.h with exactly this purpose (Git's redefines each banned name as a macro that expands to sorry_strcpy_is_a_banned_function and so fails to compile).
Pattern 5: the toolchain as a safety net
- Warnings as errors in CI:
-Wall -Wextra -Wformat=2 -Wconversion -Wsign-conversion -Wvla -Werror(Compiler Warnings). - Sanitizers and fuzzing on every change (Sanitizers in CI).
- Hardened release builds checked with
checksec(Mitigations Compared). - Bounds-safety extensions where available: Clang's
-fbounds-safety(developed at Apple) annotates pointers with their bounds (__counted_by(len)) and checks them; GCC 15 and Clang 18 accept__attribute__((counted_by(len)))on flexible array members, which FORTIFY and UBSan's-fsanitize=boundsuse.
How these patterns are checked
A reviewer can verify each pattern locally: every buffer parameter has a size next to it; every size computation is checked; every allocation has a named owner and one destroy; grep for the banned list returns nothing (and the poison header makes that automatic). Coding standards such as SEI CERT C and MISRA C encode many of the same rules, and clang-tidy's cert-* checks enforce parts of them.
Pitfalls
- Wrappers that only move the bug: a
safe_copy(dst, src, n)is only safe ifnis the capacity ofdst, not the length ofsrc. - Truncation as a silent fallback:
snprintftruncating a path or a user name can make it name something else. Check the return value and reject. - Patterns without enforcement decay. Put them in headers, linters and CI, not only in a style guide.
Practice
1. Why is while (cap < need) cap *= 2; safe from overflow in buf_append?
need is at most BUF_MAX (1 MiB), checked before the loop. Doubling from 16 stops at the first power of two ≥ need, so cap never exceeds 2 MiB, far below SIZE_MAX.
2. Why does buf_append assign realloc's result to a temporary p?
If realloc fails it returns NULL and leaves the old block allocated. Writing b->data = realloc(b->data, cap) would overwrite the only pointer to that block with NULL: a leak, and a crash on the next use.
3. Where should #pragma GCC poison go, and why after the system headers?
In a project-wide header included by every source file, after <string.h> and friends. System headers may declare or use the poisoned names (inline wrappers, FORTIFY), and poisoning them before inclusion breaks the build for the wrong reason.
Test yourself
What did buf_append return for an append of SIZE_MAX bytes?
- 0
- -1, because ckd_add detected that len + n overflows
- It crashed
- It truncated the input
What does #pragma GCC poison strcpy do?
- Replaces strcpy with strncpy
- Makes every later use of strcpy a compile error
- Logs calls to strcpy
- Adds a run-time check
Which convention prevents double frees in C?
- Never free memory
- One documented owner per object, ownership moved only on success, and destroy functions that accept NULL and clear the pointer
- free(p) twice for safety
- Global variables
Why does struct buf keep both len and cap?
- For speed only
- So every write can be checked against the allocated capacity, not just the used length
- C requires it
- To store the NUL