Defensive Programming in C: 10 Techniques with Tested Examples

Ten defensive programming techniques in C, from input validation and error codes to assert, bounds checks and sanitizers, each with tested code.

A shield stopping bad input before it reaches a program window, with a green check on the program

Defensive programming is writing code that checks its assumptions instead of trusting them: it validates input, checks every result that can fail and handles impossible states explicitly, so errors stop close to their cause instead of corrupting data later. In C this matters more than in most languages, because the language itself checks almost nothing: an unchecked atoi, a missing + 1 in a malloc or an ignored fclose compiles without a warning and fails quietly at run time.

This guide covers ten defensive programming techniques for C, from input validation and error codes to assertions, bounds checks and sanitizers. Each one comes with code from a small, tested library, and each common mistake has a program that demonstrates it. A short section at the end shows what changes in C++, with a tested C++ version of the same library. The source code and tests build with GCC, Clang and MSVC.

What Is Defensive Programming?

The term comes from defensive driving: assume that other drivers will make mistakes, and drive so that their mistakes do not become accidents. In code, the “other drivers” are users who type the wrong thing, files that are truncated or corrupted, disks that fill up, network peers that send garbage and, often, your own code from six months ago.

In practice, defensive code does four things:

  • It validates input at the point where data enters the program, and rejects what it cannot use.
  • It checks results: every call that can fail (malloc, fopen, fwrite, fclose, strtol) is checked, and failures are passed up or handled.
  • It states assumptions with assertions, so that a broken assumption stops the program in testing instead of producing a wrong answer in production.
  • It limits damage: buffers carry their sizes, arithmetic is checked before it can overflow and resources are released on every path.

The key idea is the trust boundary. Data from outside the program is untrusted and must be validated, with errors reported to the caller. Data inside the program, which your own code has already checked, is trusted, and a wrong value there is a bug to catch with an assertion.

The trust boundary in a C program Untrusted input Keyboard and argv Files Network messages Environment Validate once present? well formed? in range? bad input: return an error code with a clear message Trusted core data is already valid assert internal assumptions static_assert sizes and layouts check every call that can fail free resources on every path Tools check both sides -Wall -Werror | -fsanitize=address,undefined | -fanalyzer | valgrind warnings at compile time, sanitizers and Valgrind in tests, the analyzer on every path
Figure 1: Validate untrusted input once, at the boundary, and report errors to the caller. Inside, assert the assumptions that only a bug can break.

Getting this split wrong is the most common defensive programming mistake in both directions. Checking user input with assert crashes the program on a typo (or, in a release build, does not check at all). Checking every internal pointer with an if and a silent return hides bugs instead of finding them.

10 Defensive Programming Techniques in C

#TechniqueWhat it prevents
1Validate input at the trust boundaryBad data spreading through the program
2Parse numbers with strtol, not atoi"abc" silently read as 0
3Return error codes and check every resultFailures that go unnoticed
4Assert internal assumptionsBugs that produce wrong answers instead of stopping
5Check what you can at compile time with static_assertWrong sizes and layouts reaching run time
6Pass a size with every bufferBuffer overflows
7Check size arithmetic before allocatingAllocations too small because a multiplication overflowed
8Release resources on every pathLeaks and half-written files after an error
9Initialize variables and keep state consistentUninitialized reads
10Let the compiler, sanitizers and analyzers checkBugs that tests do not trigger

The examples share one small library, defensive.h. Every function in it returns a status code and writes its result through a pointer only on success, so a caller can never use a value that was not produced:

/* defensive.h - small, checked building blocks for C programs.
 *
 * Every function returns a dp_status. Results go through an output pointer,
 * which is written only on success, so a caller can never use a value that
 * was not produced.
 */
#ifndef DEFENSIVE_H
#define DEFENSIVE_H

#include <stddef.h>
#include <stdio.h>

/* Ask the compiler to warn when a caller ignores the returned status. */
#if defined(__GNUC__) || defined(__clang__)
#define DP_NODISCARD __attribute__((warn_unused_result))
#else
#define DP_NODISCARD
#endif

typedef enum {
    DP_OK = 0,
    DP_ERR_NULL,          /* a required pointer argument was NULL */
    DP_ERR_EMPTY,         /* the input was empty */
    DP_ERR_NOT_A_NUMBER,  /* no digits where a number was expected */
    DP_ERR_TRAILING,      /* a number followed by other characters */
    DP_ERR_RANGE,         /* a number outside the allowed range */
    DP_ERR_TOO_LONG,      /* the input does not fit the buffer */
    DP_ERR_EOF,           /* no more input */
    DP_ERR_OVERFLOW,      /* a size calculation would overflow */
    DP_ERR_NO_MEMORY,     /* malloc or calloc failed */
    DP_ERR_IO             /* a file operation failed; see errno */
} dp_status;

/* A short English description of a status code. Never returns NULL. */
const char *dp_strerror(dp_status status);

/* Parses all of text as a base-10 integer in [min, max].
 * Leading spaces are allowed; anything after the number is not. */
DP_NODISCARD dp_status dp_parse_long(const char *text, long min, long max, long *out);

/* Reads one line into buf without the newline. A line that does not fit is
 * consumed up to its newline and reported as DP_ERR_TOO_LONG. */
DP_NODISCARD dp_status dp_read_line(FILE *in, char *buf, size_t size);

/* Copies src into dst (size bytes, always terminated). Returns
 * DP_ERR_TOO_LONG if src was cut short. */
DP_NODISCARD dp_status dp_copy_string(char *dst, size_t size, const char *src);

/* *out = a * b, or DP_ERR_OVERFLOW if the product does not fit in size_t. */
DP_NODISCARD dp_status dp_mul_size(size_t a, size_t b, size_t *out);

/* Allocates count elements of size bytes each, zeroed, with an overflow check. */
DP_NODISCARD dp_status dp_alloc_array(size_t count, size_t size, void **out);

/* Copies the file at from_path to to_path. On failure, errno describes
 * the failing call and no partial output file is left behind. */
DP_NODISCARD dp_status dp_copy_file(const char *from_path, const char *to_path);

#endif

1. Validate Input at the Trust Boundary

Every value that comes from outside (command-line arguments, files, standard input, environment variables, network messages) is checked once, where it enters, before the rest of the program uses it. Validation answers three questions:

  • Is it present? Empty strings, missing fields and missing files are the most common bad input.
  • Is it well formed? A number contains only digits, a record has the right number of fields, a line is not longer than the buffer.
  • Is it in range? An age between 0 and 150, a port between 1 and 65535, an index smaller than the array.

Reading a line is the first boundary in most C programs. fgets is the safe choice because it takes the buffer size, but it does not tell you directly whether the line fit. This function does, and it consumes the rest of a long line so that the next read starts at the next line:

dp_status dp_read_line(FILE *in, char *buf, size_t size)
{
    if (in == NULL || buf == NULL) {
        return DP_ERR_NULL;
    }
    if (size < 2 || size > INT_MAX) {
        return DP_ERR_RANGE; /* fgets takes an int and needs room for one char */
    }
    if (fgets(buf, (int)size, in) == NULL) {
        buf[0] = '\0';
        return ferror(in) ? DP_ERR_IO : DP_ERR_EOF;
    }
    size_t len = strlen(buf);
    if (len > 0 && buf[len - 1] == '\n') {
        buf[--len] = '\0';
    } else if (!feof(in)) {
        /* No newline yet. If the next character ends the line, the line
         * filled the buffer exactly; otherwise it is too long. */
        int c = getc(in);
        if (c != '\n' && c != EOF) {
            while ((c = getc(in)) != EOF && c != '\n') {
            }
            buf[0] = '\0';
            return DP_ERR_TOO_LONG;
        }
    }
    if (len > 0 && buf[len - 1] == '\r') {
        buf[len - 1] = '\0'; /* a file with Windows line endings */
    }
    return DP_OK;
}

The boundary case is a line that fills the buffer exactly. With an 8-byte buffer, fgets reads a 7-character line but leaves its newline unread, so the function peeks at the next character: a newline means the line fit, anything else means it did not. The unit tests check both sides of this boundary, a 7-character line accepted and an 8-character line rejected, because a check that is off by one at the boundary rejects valid input or accepts invalid input.

2. Parse Numbers with strtol, Not atoi

atoi has no way to report an error. It returns 0 for "abc", which looks exactly like a valid "0", and it returns 12 for "12abc". A number too large for an int is undefined behavior. strtol reports all three cases, through its end pointer and errno, and this wrapper turns them into status codes:

dp_status dp_parse_long(const char *text, long min, long max, long *out)
{
    if (text == NULL || out == NULL) {
        return DP_ERR_NULL;
    }
    while (isspace((unsigned char)*text)) {
        text++;
    }
    if (*text == '\0') {
        return DP_ERR_EMPTY;
    }

    char *end = NULL;
    errno = 0;
    const long value = strtol(text, &end, 10);
    if (end == text) {
        return DP_ERR_NOT_A_NUMBER;
    }
    if (errno == ERANGE || value < min || value > max) {
        return DP_ERR_RANGE;
    }
    if (*end != '\0') {
        return DP_ERR_TRAILING;
    }
    *out = value;
    return DP_OK;
}

The order of the checks matters. end == text means no digits at all. errno == ERANGE means the number did not fit in a long; errno must be set to 0 before the call, as the strtol manual page advises, because strtol only sets it on failure. The range check comes next, and the check for trailing characters last. The program pitfalls/atoi_vs_strtol.c runs both on the same inputs:

input    atoi   dp_parse_long (range 0 to 100)
"42"     42     42
"0"      0      0
"abc"    0      error: not a number
"12abc"  12     error: extra characters after the number
""       0      error: empty input
" 7"     7      7
"-5"     -5     error: number out of range

Note that " 7" is accepted, because strtol skips leading white space, while the unit tests confirm that "7 " with a trailing space is rejected. Decide which one your input format allows, and test it.

3. Return Error Codes and Check Every Result

C has no exceptions, so a function reports failure through its return value. The convention in this library is an enum of status codes, a function that turns each code into a message and output through a pointer:

const char *dp_strerror(dp_status status)
{
    switch (status) {
    case DP_OK:               return "ok";
    case DP_ERR_NULL:         return "missing argument";
    case DP_ERR_EMPTY:        return "empty input";
    case DP_ERR_NOT_A_NUMBER: return "not a number";
    case DP_ERR_TRAILING:     return "extra characters after the number";
    case DP_ERR_RANGE:        return "number out of range";
    case DP_ERR_TOO_LONG:     return "input too long";
    case DP_ERR_EOF:          return "end of input";
    case DP_ERR_OVERFLOW:     return "size overflow";
    case DP_ERR_NO_MEMORY:    return "out of memory";
    case DP_ERR_IO:           return "input/output error";
    }
    return "unknown error"; /* a value outside the enum */
}

An error code only helps if the caller checks it. GCC and Clang can enforce that: the DP_NODISCARD macro in the header adds __attribute__((warn_unused_result)), so this call does not compile with -Werror:

/* Must not compile with -Werror on GCC or Clang: the returned status of a
 * DP_NODISCARD function is ignored, so a parse error would go unnoticed. */
#include "../src/defensive.h"

int main(void)
{
    long port = 8080;
    dp_parse_long("80x", 1, 65535, &port);
    return (int)(port % 256);
}
GCC 13:   error: ignoring return value of 'dp_parse_long' declared with attribute 'warn_unused_result' [-Werror=unused-result]
Clang 18: error: ignoring return value of function declared with 'warn_unused_result' attribute [-Werror,-Wunused-result]

One difference matters: Clang lets you silence the warning with a (void) cast, which documents a deliberate decision, but GCC still warns. C23 adds the standard [[nodiscard]] attribute; in the test run, GCC 13 and Clang 18 (with -std=c2x) both warned about an ignored result and both accepted a (void) cast.

Standard library functions report errors in their own ways, and each needs its own check:

  • malloc, calloc, fopen, fgets return NULL.
  • fclose, fflush, fputs return EOF; fprintf returns a negative number.
  • fwrite and fread return fewer items than requested; use ferror to tell an error from end of file.
  • errno says why, but only right after a call that failed. Save it before calling anything else, as the remove call in dp_copy_file below does.

4. Assert Internal Assumptions

assert(condition) stops the program with the file, line and condition when the condition is false. It is for programmer errors: conditions that cannot be false if the code is correct, such as a pointer your own function guarantees is not NULL or an index you have already range-checked. It is not for user errors, for two reasons. A user should get an error message, not a crash. And assert disappears completely when NDEBUG is defined, which most release builds do.

That second point produces a classic bug when the asserted expression does real work:

/* An assert whose condition does work. Built with NDEBUG (as release builds
 * usually are), the whole expression disappears, and so does the work. */
#include <assert.h>
#include <stdio.h>

static int items = 3;

static int take_item(void)
{
    items--;
    return items >= 0;
}

int main(void)
{
    assert(take_item()); /* WRONG: the call vanishes when NDEBUG is defined */
#ifdef NDEBUG
    printf("NDEBUG build: %d items left\n", items);
#else
    printf("debug build:  %d items left\n", items);
#endif
    return 0;
}

The test suite builds this file twice. The debug build prints:

debug build:  2 items left

The build with NDEBUG prints:

NDEBUG build: 3 items left

In the release build the item was never taken, because the call inside assert was removed with it. The fix is to do the work first and assert on the result: int ok = take_item(); assert(ok);.

5. Check at Compile Time with static_assert

Some assumptions can be checked before the program runs. C11’s static_assert (from <assert.h>) stops the compilation when a constant expression is false. It costs nothing at run time and cannot be turned off. Typical uses are the size of a type, the layout of a structure written to a file and the relationship between two constants. people.c below uses one to tie a buffer size to its constant.

A static assertion also catches surprises. This structure looks like 7 bytes, but the compiler adds a byte of padding, so the assertion fails on GCC, Clang and MSVC alike:

/* Must not compile anywhere: the static assertion documents the on-disk
 * size of a header, and padding makes the struct larger than that. */
#include <assert.h>
#include <stdint.h>

struct header {
    uint32_t magic;
    uint16_t version;
    uint8_t flags; /* the compiler adds one byte of padding after this */
};

static_assert(sizeof(struct header) == 7, "header must be 7 bytes on disk");

int main(void)
{
    return 0;
}
GCC 13:   error: static assertion failed: "header must be 7 bytes on disk"
Clang 18: error: static assertion failed due to requirement 'sizeof(struct header) == 7': header must be 7 bytes on disk

6. Pass a Size with Every Buffer

Most buffer overflows in C come from a function that writes to a buffer without knowing its size: gets (removed from the language in C11), strcpy, strcat and sprintf. The defensive rule is simple: every pointer to a buffer travels with its size, and every write checks it.

  • Use fgets instead of gets and snprintf instead of sprintf. Check snprintf‘s return value: a result greater than or equal to the buffer size means the output was cut short.
  • Be careful with strncpy: when the source is too long, it does not add the terminating zero.
  • Write sizeof buffer where the array is declared, not a repeated number, and remember that sizeof on a pointer parameter gives the size of the pointer, not the array.

This copy function always terminates the result and reports truncation, so the caller decides whether a shortened string is acceptable:

dp_status dp_copy_string(char *dst, size_t size, const char *src)
{
    if (dst == NULL || src == NULL) {
        return DP_ERR_NULL;
    }
    if (size == 0) {
        return DP_ERR_TOO_LONG;
    }
    const size_t len = strlen(src);
    const size_t n = len < size ? len : size - 1;
    memcpy(dst, src, n);
    dst[n] = '\0';
    return n == len ? DP_OK : DP_ERR_TOO_LONG;
}

C11’s optional Annex K defines strcpy_s and similar “safe” functions, but glibc and the other common C libraries on Linux and macOS do not provide them, and Microsoft’s versions differ from the standard, so portable code usually writes small functions like this one.

7. Check Size Arithmetic Before Allocating

malloc(count * size) has a hidden bug: if the multiplication overflows size_t, the result wraps around to a small number, malloc succeeds and the program writes far past the end of a small allocation. With count coming from a file header or a network message, this is a classic security hole. Check the multiplication first:

dp_status dp_mul_size(size_t a, size_t b, size_t *out)
{
    if (out == NULL) {
        return DP_ERR_NULL;
    }
    if (b != 0 && a > SIZE_MAX / b) {
        return DP_ERR_OVERFLOW;
    }
    *out = a * b;
    return DP_OK;
}
dp_status dp_alloc_array(size_t count, size_t size, void **out)
{
    if (out == NULL) {
        return DP_ERR_NULL;
    }
    size_t bytes;
    const dp_status st = dp_mul_size(count, size, &bytes);
    if (st != DP_OK) {
        return st;
    }
    void *p = calloc(count == 0 ? 1 : count, size == 0 ? 1 : size);
    if (p == NULL) {
        return DP_ERR_NO_MEMORY;
    }
    *out = p;
    return DP_OK;
}

Modern C libraries make the same check inside calloc, but an explicit check gives a clear error code and works for realloc too, which has no such check. C23 adds ckd_mul in <stdckdint.h> for the same purpose, and GCC and Clang offer __builtin_mul_overflow.

The same care applies to signed arithmetic. Signed overflow is undefined behavior in C, so total += 1 with total == INT_MAX is a bug even if it seems to work. Check against INT_MAX before adding, or use a wider type.

8. Release Resources on Every Path

Error handling in C means returning early, and every early return must release what the function has acquired so far. The common C idiom is a single cleanup block at the end of the function, reached with goto. It keeps the success path readable and makes it hard to forget one resource on one error path:

dp_status dp_copy_file(const char *from_path, const char *to_path)
{
    if (from_path == NULL || to_path == NULL) {
        return DP_ERR_NULL;
    }
    dp_status status = DP_ERR_IO;
    FILE *in = NULL;
    FILE *out = NULL;
    int created = 0; /* set once to_path has been opened for writing */
    char buffer[4096];

    in = fopen(from_path, "rb");
    if (in == NULL) {
        goto cleanup;
    }
    out = fopen(to_path, "wb");
    if (out == NULL) {
        goto cleanup;
    }
    created = 1;
    size_t n;
    while ((n = fread(buffer, 1, sizeof buffer, in)) > 0) {
        if (fwrite(buffer, 1, n, out) != n) {
            goto cleanup;
        }
    }
    if (ferror(in)) {
        goto cleanup;
    }
    /* fclose flushes the last buffer, so its result matters too. */
    const int close_failed = fclose(out);
    out = NULL;
    if (close_failed != 0) {
        goto cleanup;
    }
    status = DP_OK;

cleanup:
    if (in != NULL) {
        fclose(in);
    }
    if (out != NULL) {
        fclose(out);
    }
    if (status != DP_OK && created) {
        const int saved = errno;
        remove(to_path); /* do not leave a half-written copy */
        errno = saved;
    }
    return status;
}

Four details make this function defensive rather than merely correct:

  • The result of fclose is checked for the output file, because fclose writes the last buffered data and can fail on a full disk.
  • ferror(in) is checked after the read loop, because fread returns 0 for both end of file and a read error.
  • A failed copy deletes its partial output, so no half-written file is mistaken for a good one. The created flag ensures that a failure to open the input never deletes an existing file at the output path; a deliberate mistake in the test suite removes the flag, and the tests catch it.
  • errno is saved around remove, so the caller still sees why the copy failed.

9. Initialize Variables and Keep State Consistent

An uninitialized local variable holds whatever was in that memory, and reading it is undefined behavior. Initialize variables where you declare them, even when you believe every path sets them. When GCC’s static analyzer (-fanalyzer) checked people.c below, it could not prove that every path set a record before it was printed, and reported a possible uninitialized read. Initializing the record where it is declared costs nothing and removed the warning.

The same principle applies to state that outlives a function:

  • Write outputs only on success, as every function in defensive.h does, so a failed call leaves the caller’s variable unchanged.
  • Set a pointer to NULL after free when the pointer lives on, so a second free does nothing and a later use fails clearly.
  • Give every switch on an enum a path for unexpected values, as dp_strerror does after its switch.

10. Let the Compiler, Sanitizers and Analyzers Check

Defensive code reduces bugs; tools find the ones that remain. Each of these programs in the pitfalls folder contains one classic bug, and the table shows what caught it in the test run:

BugNormal buildCaught by
malloc(strlen(s)) then strcpy: one byte too fewRan, printed the right text, exit status 0AddressSanitizer: heap-buffer-overflow
Reading memory after freeNot run (undefined behavior)GCC 13 -Wall at compile time (-Wuse-after-free); AddressSanitizer: heap-use-after-free
INT_MAX + 1Not run (undefined behavior)UndefinedBehaviorSanitizer: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
malloc, then an early return when fopen failsRan normallyGCC -fanalyzer without running it: leak of 'buffer' [-Wanalyzer-malloc-leak]

The first row is the important one: the off-by-one program worked in a normal build. Memory bugs in C often stay invisible until a different input, compiler or platform turns them into a crash or a security hole. That is why the tools belong in every build, not only in a crisis:

  • Warnings: compile with -Wall -Wextra -Wpedantic -Wconversion -Werror (GCC, Clang) or /W4 /WX (MSVC). -Wconversion finds silent narrowing such as a size_t stored in an int.
  • Sanitizers: run the test suite with -fsanitize=address,undefined on GCC and Clang, or /fsanitize=address on MSVC. AddressSanitizer’s typical slowdown is 2x, which is fine for tests.
  • Static analysis: GCC’s -fanalyzer, clang-tidy and MSVC’s /analyze find bugs on paths that tests never execute, such as error paths.
  • Valgrind finds leaks and invalid reads in an unmodified Linux build.
  • Hardening for release builds: -D_FORTIFY_SOURCE=3 and -fstack-protector-strong add cheap run-time checks to production binaries.

The output for the off-by-one program, shortened:

ERROR: AddressSanitizer: heap-buffer-overflow on address ...
WRITE of size 10 at ... thread T0
SUMMARY: AddressSanitizer: heap-buffer-overflow ... in strcpy

“WRITE of size 10” is the string "defensive" plus its terminator, written into a 9-byte allocation.

Putting It Together: Validating a File of Records

people.c reads name,age records and uses the library at every step: dp_read_line for long lines, dp_parse_long for the age, a size check for the name, a static_assert for the buffer and an error message with a line number for every rejected record:

/* people: reads "name,age" lines, rejects bad records with a reason and a
 * line number, and prints the valid ones. Usage: people FILE */
#include "defensive.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

#define NAME_MAX_LEN 32
#define LINE_MAX_LEN 80

typedef struct {
    char name[NAME_MAX_LEN + 1];
    long age;
} person;

/* Checked when compiling: parse_person relies on this. */
static_assert(sizeof(((person *)0)->name) == NAME_MAX_LEN + 1,
              "name must hold NAME_MAX_LEN characters and the terminator");

/* Splits "name,age" and validates both fields.
 * Returns NULL on success, otherwise the reason the record was rejected. */
static const char *parse_person(const char *line, person *out)
{
    if (line[0] == '\0') {
        return "empty line";
    }
    const char *comma = strchr(line, ',');
    if (comma == NULL) {
        return "missing comma";
    }
    const size_t name_len = (size_t)(comma - line);
    if (name_len == 0) {
        return "empty name";
    }
    if (name_len > NAME_MAX_LEN) {
        return "name longer than 32 characters";
    }
    long age;
    const dp_status st = dp_parse_long(comma + 1, 0, 150, &age);
    if (st != DP_OK) {
        return dp_strerror(st);
    }
    memcpy(out->name, line, name_len);
    out->name[name_len] = '\0';
    out->age = age;
    return NULL;
}

int main(int argc, char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s FILE\n", argv[0]);
        return 2;
    }
    FILE *in = fopen(argv[1], "r");
    if (in == NULL) {
        fprintf(stderr, "%s: %s\n", argv[1], strerror(errno));
        return 1;
    }

    char line[LINE_MAX_LEN + 1]; /* 80 characters and the terminator */
    unsigned long number = 0;
    int accepted = 0;
    int rejected = 0;
    dp_status st;
    while ((st = dp_read_line(in, line, sizeof line)) != DP_ERR_EOF) {
        number++;
        person p = {{0}, 0}; /* initialized, so no path can print garbage */
        const char *why = NULL;
        if (st == DP_ERR_TOO_LONG) {
            why = "line longer than 80 characters";
        } else if (st != DP_OK) {
            why = dp_strerror(st);
        } else if ((why = parse_person(line, &p)) == NULL) {
            printf("ok    line %lu: %s, %ld\n", number, p.name, p.age);
            accepted++;
            continue;
        }
        printf("error line %lu: %s\n", number, why);
        rejected++;
        if (st == DP_ERR_IO) {
            break;
        }
    }
    const int read_failed = ferror(in);
    fclose(in);
    printf("%d accepted, %d rejected\n", accepted, rejected);
    return (rejected == 0 && !read_failed) ? 0 : 1;
}

The test file contains two valid records, every kind of bad record the program checks for, a line with Windows line endings and a last line without a newline. The output:

ok    line 1: Ada Lovelace, 36
ok    line 2: Alan Turing, 41
error line 3: empty line
error line 4: missing comma
error line 5: empty name
error line 6: not a number
error line 7: extra characters after the number
error line 8: number out of range
error line 9: number out of range
error line 10: number out of range
ok    line 11: Barbara Liskov, 86
error line 12: name longer than 32 characters
error line 13: line longer than 80 characters
ok    line 14: Edsger, 72
ok    line 15: Niklaus, 89
5 accepted, 10 rejected

Two details are worth noticing. The program keeps going after a bad record and reports all of them, which is what a user fixing a file wants. And it returns exit status 1 when any record was rejected, so a script that runs it can tell that something was wrong.

Defensive Programming in C++: What Changes

The same techniques apply in C++, but the standard library takes over much of the bookkeeping. The repository includes a C++ version of the library and of people, and the C++ people must print exactly the same report as the C one: both test suites compare against the same expected output file.

TechniqueCC++
Parse numbersstrtol with errno and the end pointerstd::from_chars: no errno, no locale, never throws
Force callers to check resultswarn_unused_result (GCC, Clang) or C23 [[nodiscard]][[nodiscard]], standard since C++17
Buffers and sizesA size passed with every pointerstd::string, std::vector and std::string_view carry their size
Bounds checksExplicit if before every indexat() throws std::out_of_range
Release resourcesgoto cleanupRAII: destructors close files and free memory on every path
Errors with valuesStatus code plus an output pointerstd::optional, or std::expected in C++23

The C++ parser is shorter because std::from_chars reports both “no digits” and “out of range” in its result. It does not skip white space or accept a leading +, so the function handles both to match the C version:

Status parse_long(std::string_view text, long min, long max, long& out) noexcept
{
    const auto first = text.find_first_not_of(" \t\n\v\f\r");
    if (first == std::string_view::npos) {
        return Status::empty;
    }
    text.remove_prefix(first);
    if (text.size() > 1 && text[0] == '+' && text[1] != '-') {
        text.remove_prefix(1); // from_chars does not accept a '+' sign
    }
    long value = 0;
    // from_chars never throws, ignores the locale and reports where it stopped.
    const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
    if (error == std::errc::invalid_argument) {
        return Status::not_a_number;
    }
    if (error == std::errc::result_out_of_range || value < min || value > max) {
        return Status::range;
    }
    if (end != text.data() + text.size()) {
        return Status::trailing;
    }
    out = value;
    return Status::ok;
}

The file copy needs no cleanup block: the streams close themselves when they go out of scope, on every return path. Two checks remain the programmer’s job, and both are easy to miss in C++ too:

Status copy_file(const std::string& from_path, const std::string& to_path)
{
    std::ifstream in(from_path, std::ios::binary);
    if (!in) {
        return Status::io; // nothing created yet, so nothing to clean up
    }
    {
        std::ofstream out(to_path, std::ios::binary);
        if (!out) {
            return Status::io;
        }
        char buffer[4096];
        while (in.read(buffer, sizeof buffer) || in.gcount() > 0) {
            if (!out.write(buffer, in.gcount())) {
                break;
            }
        }
        const bool read_failed = in.bad();
        out.close(); // flush now, so a full disk is detected here
        if (read_failed || out.fail()) {
            std::remove(to_path.c_str()); // do not leave a half-written copy
            return Status::io;
        }
    } // the streams close themselves on every path: no goto needed
    return Status::ok;
}
  • The output stream is closed explicitly before the check, so a write error during the final flush is seen.
  • The copy loop is explicit. The shorter out << in.rdbuf(); sets the output stream’s failure flag when the input file is empty, so a correct copy of an empty file would be reported as an error. The unit tests copy an empty file to catch exactly this.

[[nodiscard]] is also more useful in C++ than its C counterpart: it is part of the standard, so the same code that fails with GCC and Clang (error: ignoring return value ... declared with attribute 'nodiscard') also fails on MSVC with /W4 /WX, which reports warning C4834.

Common Defensive Programming Mistakes

  • Using assert to check user input. It crashes on bad input, and in a release build it does not check at all.
  • Putting work inside assert. The work disappears with NDEBUG, as shown above.
  • Checking errno without a failed call. errno keeps its old value on success, so set it to 0 first, as dp_parse_long does, or check it only after a failure.
  • Ignoring the result of fclose on a file you wrote. The last data is written when the file is closed.
  • Hiding bugs with silent defaults. Returning 0 or an empty string when something impossible happens keeps the program running with wrong data. Return an error, or assert.
  • Checking the same thing at every level. Validate once at the boundary, then trust the data inside; checks repeated in every function make the code harder to read without making it safer.

Frequently Asked Questions

Key Takeaways

  • Validate everything that enters the program at the trust boundary, and report errors to the caller.
  • Use strtol with errno and the end pointer instead of atoi, and test both sides of every boundary.
  • Return status codes, write outputs only on success and use warn_unused_result or C23 [[nodiscard]] so callers cannot ignore them.
  • Use assert for bugs and never for user input; never put work inside it.
  • Pass a size with every buffer, and check size arithmetic before malloc.
  • Release resources on every path with a single cleanup block, and check fclose on files you write.
  • Run tests with warnings as errors, AddressSanitizer, UBSan and a static analyzer: the off-by-one bug in this guide worked until a sanitizer stopped it.

Conclusion

Defensive programming in C comes down to one habit: never let a value or a result go unchecked just because it is usually fine. Validate input once, at the edge of the program; check every call that can fail; state your assumptions with assertions; and let the compiler and sanitizers look for the bugs that remain. None of these techniques is expensive, and together they turn silent memory corruption into a clear error message close to its cause. For a complete rule set, the SEI CERT C Coding Standard organizes its rules by topic, including error handling, integers and strings.

The techniques build on the fundamentals of the language: safe input and output in C for reading data, malloc, calloc and free for checked allocation, and file handling in C for checking every file operation. For the bigger question of when a program should stop and when it should carry on, see errors: to fail or to recover. More C tutorials are in the C programming section.

Source Code and Tests

C defensive programming build status
C++ defensive programming build status

The complete code is on GitHub:

Build and test either version (CMake 3.20 or later; on Windows, use a Developer PowerShell):

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

What the tests check.

  • Unit tests: 72 checks of the library, including both sides of every buffer and range boundary, NULL arguments and a failed file copy.
  • Program output: people, the atoi comparison and both builds of the assert example must print exactly the recorded output.
  • Code that must not compile: the ignored status (GCC and Clang) and the failing static_assert (all compilers).
  • Tools: the sanitizers must stop the three memory bugs, and -fanalyzer must report the leak and nothing in the library.
  • C++ version: 53 unit checks, the shared people output, the at() example and the [[nodiscard]] compile-fail test.
  • Deliberate mistakes: four changes to each library, each of which must make a test fail.

What I Verified

All results come from run_all.sh (Linux) and run_all.ps1 (Windows) in the two repositories, run for this article.

CheckLinux (Ubuntu 24.04)Windows 11
Build with warnings as errorsGCC 13.3 and Clang 18.1, C11 and C17, -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Wformat=2 -Werror: passedMSVC 19.44, C11 and C17, /W4 /WX: passed
CTest: 72 unit checks, 4 output comparisons, 2 compile-fail testsPassed with both compilers and both standardsPassed with both standards
AddressSanitizer and UBSanCTest passed; the off-by-one, the read after free and INT_MAX + 1 were each stoppedMSVC /fsanitize=address: CTest passed; the off-by-one (heap-buffer-overflow) and the read after free (heap-use-after-free) were stopped. MSVC has no UBSan
Valgrind memcheck (unit tests and people)No errors, no leaksNot applicable
GCC -fanalyzerReported the leak in leak_on_error.c; nothing in defensive.c or people.cNot applicable
Deliberate mistakes that a test must catch4 of 4 caught4 of 4 caught
C++ version: build and CTest (53 unit checks, shared people output, at(), [[nodiscard]] compile-fail)GCC 13.3 and Clang 18.1, C++17 and C++20, warnings as errors: passed; ASan, UBSan and Valgrind cleanMSVC 19.44, C++17 and C++20, /W4 /WX: passed, including the [[nodiscard]] compile-fail test
C++ version: deliberate mistakes4 of 4 caught4 of 4 caught

Not covered: C23 compilers in C23 mode (only the [[nodiscard]] check used -std=c2x), MSVC’s /analyze or platforms other than x86-64.

Scroll to Top