Skip to main content
Be Bitwise
CSecurity-Focused C

Defensive Programming

Defensive programming is the discipline of writing code that expects failure and handles it without melting down. It's what separates a program that crashes mysteriously at 3am from one that fails loudly with an error message that tells you exactly where to look.

Assertions: Catching Programmer Errors

Assertions check conditions that should always hold. Their job is catching bugs during development, not in front of users:

c
#include <assert.h>
void process_buffer(const char *buf, size_t len) {
assert(buf != NULL);
assert(len > 0);
assert(len <= MAX_BUFFER_SIZE);
// ...
}

Compile with -DNDEBUG and assertions evaporate in release builds. They're meant for programmer errors — broken invariants — not for user errors like garbled input.

Key Concept

Use assertions for invariants — conditions that must hold if your code is correct — and use real error handling for expected failures like a full disk, a network timeout, or bad user input. An assertion firing means you have a bug, full stop.

Error Handling Patterns

C doesn't ship with exceptions, so error handling rides on return values. A handful of patterns are in common use:

Pattern 1: Return codes

c
typedef enum {
OK = 0,
ERR_NULL_PTR = -1,
ERR_OUT_OF_MEMORY = -2,
ERR_INVALID_ARG = -3,
ERR_IO = -4,
} ErrorCode;
ErrorCode read_config(const char *path, Config *out) {
if (path == NULL || out == NULL) return ERR_NULL_PTR;
FILE *f = fopen(path, "r");
if (f == NULL) return ERR_IO;
// Parse config...
fclose(f);
return OK;
}
// Caller:
ErrorCode err = read_config("app.conf", &config);
if (err != OK) {
fprintf(stderr, "Failed to read config: %d\n", err);
return 1;
}

Pattern 2: errno-style

c
#include <errno.h>
void *my_alloc(size_t size) {
if (size == 0) {
errno = EINVAL;
return NULL;
}
void *p = malloc(size);
if (p == NULL) {
errno = ENOMEM;
}
return p;
}

Pattern 3: Result struct

c
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
typedef struct {
int ok;
union {
int value;
const char *error;
};
} Result;
Result parse_int(const char *str) {
char *end;
errno = 0;
long val = strtol(str, &end, 10);
if (errno != 0 || *end != '\0') {
return (Result){ .ok = 0, .error = "Invalid integer" };
}
if (val < INT_MIN || val > INT_MAX) {
return (Result){ .ok = 0, .error = "Integer out of range" };
}
return (Result){ .ok = 1, .value = (int)val };
}

Fail-Fast vs Fail-Safe

Fail-fast: spot an error, terminate now. Right call during development and when you're dealing with programmer errors:

c
void *checked_malloc(size_t size) {
void *p = malloc(size);
if (p == NULL) {
fprintf(stderr, "FATAL: Out of memory allocating %zu bytes\n", size);
abort();
}
return p;
}

Fail-safe: keep running, just in a degraded mode. Right call for most production systems:

c
int process_request(Request *req) {
if (req == NULL) {
log_error("Null request, skipping");
return -1;
}
Config *cfg = load_config();
if (cfg == NULL) {
log_warning("Config unavailable, using defaults");
cfg = &default_config;
}
// Continue with degraded functionality
return handle(req, cfg);
}

Degrading to defaults is fine for things like a page size or a log level. For anything that guards access, fail closed instead: if the file listing who's allowed in can't be loaded, the safe default is to let nobody in.

Defensive Copies

When a function gets handed a pointer to data it doesn't own, sometimes the safest move is a defensive copy:

c
typedef struct {
char *name;
int value;
} Entry;
// DANGEROUS: stores the caller's pointer directly
void set_entry_bad(Entry *e, char *name) {
e->name = name; // Caller might free or modify name later
}
// SAFE: makes a defensive copy
int set_entry_safe(Entry *e, const char *name) {
char *copy = strdup(name);
if (copy == NULL) return -1;
free(e->name);
e->name = copy;
return 0;
}

Sanitizing Data at Trust Boundaries

A trust boundary is anywhere data steps from an untrusted source into your code: user input, network data, file contents, environment variables, shared memory.

c
// Trust boundary: data from network
int handle_message(const char *raw, size_t raw_len) {
// 1. Validate length
if (raw_len < HEADER_SIZE || raw_len > MAX_MESSAGE_SIZE) {
return ERR_INVALID_LENGTH;
}
// 2. Parse header
MessageHeader header;
memcpy(&header, raw, sizeof(header));
// 3. Validate header fields
if (header.version != PROTOCOL_VERSION) {
return ERR_INVALID_VERSION;
}
if (header.payload_len > raw_len - HEADER_SIZE) {
return ERR_INVALID_PAYLOAD_SIZE;
}
// 4. Validate payload content
const char *payload = raw + HEADER_SIZE;
if (!is_valid_utf8(payload, header.payload_len)) {
return ERR_INVALID_ENCODING;
}
// 5. Now safe to process
return process_validated_message(&header, payload);
}

Cleanup on Error with goto

goto has had a bad reputation since Dijkstra's 1968 letter, and mostly deservedly so. But it has one widely-used, entirely legitimate role in C: error cleanup.

c
int process_file(const char *path) {
int result = -1;
FILE *f = NULL;
char *buffer = NULL;
f = fopen(path, "r");
if (f == NULL) goto cleanup;
buffer = malloc(4096);
if (buffer == NULL) goto cleanup;
size_t n = fread(buffer, 1, 4096, f);
if (n == 0) goto cleanup;
// Process buffer...
result = 0;
cleanup:
free(buffer);
if (f) fclose(f);
return result;
}

Whichever step blows up, every resource gets released exactly once. The Linux kernel runs on this pattern, and so does pretty much any serious C project.

Now do it yourself. shout_first_line below uses early returns, and three of its four failure paths leak. The harness wraps malloc, free, fopen and fclose so it can count live resources and force the Nth acquisition to fail, a poor man's Valgrind. Rewrite the function in the goto-cleanup style until every row says leaked=0.

Try itRefactor shout_first_line to a single cleanup label. main and the harness stay as they are.
C (GCC 9.2.0)
Show one answer
c
int shout_first_line(const char *path, char **out) {
int result = -1;
FILE *f = NULL;
char *line = NULL;
char *copy = NULL;
f = fopen(path, "r");
if (f == NULL) goto cleanup;
line = malloc(256);
if (line == NULL) goto cleanup;
if (fgets(line, 256, f) == NULL) goto cleanup;
size_t len = strlen(line);
copy = malloc(len + 1);
if (copy == NULL) goto cleanup;
for (size_t i = 0; i <= len; i++)
copy[i] = (char)toupper((unsigned char)line[i]);
*out = copy;
copy = NULL; // ownership has moved to the caller
result = 0;
cleanup:
free(copy);
free(line);
if (f) fclose(f);
return result;
}

Initialising every resource to NULL up front is what makes the single exit work: free(NULL) is a no-op, so the cleanup block doesn't need to know how far the function got.

Canary Values

A canary is a sentinel value tucked just before or after a buffer to catch overflows:

c
#define CANARY 0xDEADBEEF
typedef struct {
uint32_t canary_start;
char data[256];
uint32_t canary_end;
} SafeBuffer;
void init_buffer(SafeBuffer *buf) {
buf->canary_start = CANARY;
buf->canary_end = CANARY;
memset(buf->data, 0, sizeof(buf->data));
}
void check_buffer(SafeBuffer *buf) {
assert(buf->canary_start == CANARY && "Buffer underflow detected!");
assert(buf->canary_end == CANARY && "Buffer overflow detected!");
}

Modern compilers automate stack canaries via -fstack-protector, but the underlying idea still earns its keep when you're protecting hand-rolled data structures.

Putting It Into Practice

Defensive programming is plain realism. In any production system:

  1. External data is hostile: validate everything at trust boundaries
  2. Memory allocation can fail: check every malloc, calloc, realloc
  3. Files and sockets can fail: check every open, read, write
  4. Document invariants: lean on assertions to keep yourself honest
  5. Clean up resources: goto-cleanup or a wrapper function — pick one and stick with it
  6. Log errors with context: spell out what you expected and what you actually got