Monday, November 23, 2026
HomeC ProgrammingDefensive Programming Methods in C: 10 Examined Examples

Defensive Programming Methods in C: 10 Examined Examples


Defensive programming is writing code that checks its assumptions as an alternative of trusting them: it validates enter, checks each outcome that may fail and handles inconceivable states explicitly, so errors cease near their trigger as an alternative of corrupting knowledge later. In C this issues greater than in most languages, as a result of the language itself checks nearly nothing: an unchecked atoi, a lacking + 1 in a malloc or an ignored fclose compiles and not using a warning and fails quietly at run time.

This information covers ten defensive programming strategies for C, from enter validation and error codes to assertions, bounds checks and sanitizers. Each comes with code from a small, examined library, and every frequent mistake has a program that demonstrates it. A brief part on the finish exhibits what modifications in C++, with a examined C++ model of the identical library. The supply code and checks construct with GCC, Clang and MSVC.

What Is Defensive Programming?

The time period comes from defensive driving: assume that different drivers will make errors, and drive in order that their errors don’t grow to be accidents. In code, the “different drivers” are customers who kind the mistaken factor, recordsdata which are truncated or corrupted, disks that refill, community friends that ship rubbish and, typically, your personal code from six months in the past.

In apply, defensive code does 4 issues:

  • It validates enter on the level the place knowledge enters this system, and rejects what it can’t use.
  • It checks outcomes: each name that may fail (malloc, fopen, fwrite, fclose, strtol) is checked, and failures are handed up or dealt with.
  • It states assumptions with assertions, so {that a} damaged assumption stops this system in testing as an alternative of manufacturing a mistaken reply in manufacturing.
  • It limits injury: buffers carry their sizes, arithmetic is checked earlier than it may possibly overflow and sources are launched on each path.

The important thing concept is the belief boundary. Knowledge from outdoors this system is untrusted and have to be validated, with errors reported to the caller. Knowledge inside this system, which your personal code has already checked, is trusted, and a mistaken worth there’s a bug to catch with an assertion.

The belief boundary in a C program Untrusted enter Keyboard and argv Information Community messages Surroundings Validate as soon as current? nicely shaped? in vary? unhealthy enter: return an error code with a transparent message Trusted core knowledge is already legitimate assert inside assumptions static_assert sizes and layouts examine each name that may fail free sources on each path Instruments examine each side -Wall -Werror | -fsanitize=handle,undefined | -fanalyzer | valgrind warnings at compile time, sanitizers and Valgrind in checks, the analyzer on each path
Determine 1: Validate untrusted enter as soon as, on the boundary, and report errors to the caller. Inside, assert the assumptions that solely a bug can break.

Getting this cut up mistaken is the most typical defensive programming mistake in each instructions. Checking person enter with assert crashes this system on a typo (or, in a launch construct, doesn’t examine in any respect). Checking each inside pointer with an if and a silent return hides bugs as an alternative of discovering them.

10 Defensive Programming Methods in C

# Approach What it prevents
1 Validate enter on the belief boundary Dangerous knowledge spreading by this system
2 Parse numbers with strtol, not atoi "abc" silently learn as 0
3 Return error codes and examine each outcome Failures that go unnoticed
4 Assert inside assumptions Bugs that produce mistaken solutions as an alternative of stopping
5 Verify what you possibly can at compile time with static_assert Improper sizes and layouts reaching run time
6 Move a measurement with each buffer Buffer overflows
7 Verify measurement arithmetic earlier than allocating Allocations too small as a result of a multiplication overflowed
8 Launch sources on each path Leaks and half-written recordsdata after an error
9 Initialize variables and maintain state constant Uninitialized reads
10 Let the compiler, sanitizers and analyzers examine Bugs that checks don’t set off

The examples share one small library, defensive.h. Each perform in it returns a standing code and writes its outcome by a pointer solely on success, so a caller can by no means use a price that was not produced:

/* defensive.h - small, checked constructing blocks for C applications.
 *
 * Each perform returns a dp_status. Outcomes undergo an output pointer,
 * which is written solely on success, so a caller can by no means use a price that
 * was not produced.
 */
#ifndef DEFENSIVE_H
#outline DEFENSIVE_H

#embody <stddef.h>
#embody <stdio.h>

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

typedef enum {
    DP_OK = 0,
    DP_ERR_NULL,          /* a required pointer argument was NULL */
    DP_ERR_EMPTY,         /* the enter was empty */
    DP_ERR_NOT_A_NUMBER,  /* no digits the place a quantity was anticipated */
    DP_ERR_TRAILING,      /* a quantity adopted by different characters */
    DP_ERR_RANGE,         /* a quantity outdoors the allowed vary */
    DP_ERR_TOO_LONG,      /* the enter doesn't match the buffer */
    DP_ERR_EOF,           /* no extra enter */
    DP_ERR_OVERFLOW,      /* a measurement calculation would overflow */
    DP_ERR_NO_MEMORY,     /* malloc or calloc failed */
    DP_ERR_IO             /* a file operation failed; see errno */
} dp_status;

/* A brief English description of a standing code. By no means returns NULL. */
const char *dp_strerror(dp_status standing);

/* Parses all of textual content as a base-10 integer in [min, max].
 * Main areas are allowed; something after the quantity isn't. */
DP_NODISCARD dp_status dp_parse_long(const char *textual content, lengthy min, lengthy max, lengthy *out);

/* Reads one line into buf with out the newline. A line that doesn't match is
 * consumed as much as its newline and reported as DP_ERR_TOO_LONG. */
DP_NODISCARD dp_status dp_read_line(FILE *in, char *buf, size_t measurement);

/* Copies src into dst (measurement bytes, all the time terminated). Returns
 * DP_ERR_TOO_LONG if src was minimize quick. */
DP_NODISCARD dp_status dp_copy_string(char *dst, size_t measurement, const char *src);

/* *out = a * b, or DP_ERR_OVERFLOW if the product doesn't slot in size_t. */
DP_NODISCARD dp_status dp_mul_size(size_t a, size_t b, size_t *out);

/* Allocates depend parts of measurement bytes every, zeroed, with an overflow examine. */
DP_NODISCARD dp_status dp_alloc_array(size_t depend, size_t measurement, void **out);

/* Copies the file at from_path to to_path. On failure, errno describes
 * the failing name 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 Enter on the Belief Boundary

Each worth that comes from outdoors (command-line arguments, recordsdata, normal enter, atmosphere variables, community messages) is checked as soon as, the place it enters, earlier than the remainder of this system makes use of it. Validation solutions three questions:

  • Is it current? Empty strings, lacking fields and lacking recordsdata are the most typical unhealthy enter.
  • Is it nicely shaped? A quantity comprises solely digits, a document has the appropriate variety of fields, a line isn’t longer than the buffer.
  • Is it in vary? An age between 0 and 150, a port between 1 and 65535, an index smaller than the array.

Studying a line is the primary boundary in most C applications. fgets is the secure selection as a result of it takes the buffer measurement, however it doesn’t let you know straight whether or not the road match. This perform does, and it consumes the remainder of an extended line in order that the subsequent learn begins on the subsequent line:

dp_status dp_read_line(FILE *in, char *buf, size_t measurement)
{
    if (in == NULL || buf == NULL) {
        return DP_ERR_NULL;
    }
    if (measurement < 2 || measurement > INT_MAX) {
        return DP_ERR_RANGE; /* fgets takes an int and desires room for one char */
    }
    if (fgets(buf, (int)measurement, in) == NULL) {
        buf[0] = '';
        return ferror(in) ? DP_ERR_IO : DP_ERR_EOF;
    }
    size_t len = strlen(buf);
    if (len > 0 && buf[len - 1] == 'n') {
        buf[--len] = '';
    } else if (!feof(in)) {
        /* No newline but. If the subsequent character ends the road, the road
         * stuffed the buffer precisely; in any other case it's too lengthy. */
        int c = getc(in);
        if (c != 'n' && c != EOF) {
            whereas ((c = getc(in)) != EOF && c != 'n') {
            }
            buf[0] = '';
            return DP_ERR_TOO_LONG;
        }
    }
    if (len > 0 && buf[len - 1] == 'r') {
        buf[len - 1] = ''; /* a file with Home windows line endings */
    }
    return DP_OK;
}

The boundary case is a line that fills the buffer precisely. With an 8-byte buffer, fgets reads a 7-character line however leaves its newline unread, so the perform peeks on the subsequent character: a newline means the road match, the rest means it didn’t. The unit checks examine each side of this boundary, a 7-character line accepted and an 8-character line rejected, as a result of a examine that’s off by one on the boundary rejects legitimate enter or accepts invalid enter.

2. Parse Numbers with strtol, Not atoi

atoi has no strategy to report an error. It returns 0 for "abc", which appears to be like precisely like a sound "0", and it returns 12 for "12abc". A quantity too giant for an int is undefined habits. strtol studies all three instances, by its finish pointer and errno, and this wrapper turns them into standing codes:

dp_status dp_parse_long(const char *textual content, lengthy min, lengthy max, lengthy *out)
{
    if (textual content == NULL || out == NULL) {
        return DP_ERR_NULL;
    }
    whereas (isspace((unsigned char)*textual content)) {
        textual content++;
    }
    if (*textual content == '') {
        return DP_ERR_EMPTY;
    }

    char *finish = NULL;
    errno = 0;
    const lengthy worth = strtol(textual content, &finish, 10);
    if (finish == textual content) {
        return DP_ERR_NOT_A_NUMBER;
    }
    if (errno == ERANGE || worth < min || worth > max) {
        return DP_ERR_RANGE;
    }
    if (*finish != '') {
        return DP_ERR_TRAILING;
    }
    *out = worth;
    return DP_OK;
}

The order of the checks issues. finish == textual content means no digits in any respect. errno == ERANGE means the quantity didn’t slot in a lengthy; errno have to be set to 0 earlier than the decision, because the strtol guide web page advises, as a result of strtol solely units it on failure. The vary examine comes subsequent, and the examine for trailing characters final. This system pitfalls/atoi_vs_strtol.c runs each on the identical inputs:

enter    atoi   dp_parse_long (vary 0 to 100)
"42"     42     42
"0"      0      0
"abc"    0      error: not a quantity
"12abc"  12     error: additional characters after the quantity
""       0      error: empty enter
" 7"     7      7
"-5"     -5     error: quantity out of vary

Be aware that " 7" is accepted, as a result of strtol skips main white area, whereas the unit checks affirm that "7 " with a trailing area is rejected. Resolve which one your enter format permits, and check it.

3. Return Error Codes and Verify Each Consequence

C has no exceptions, so a perform studies failure by its return worth. The conference on this library is an enum of standing codes, a perform that turns every code right into a message and output by a pointer:

const char *dp_strerror(dp_status standing)
{
    change (standing) {
    case DP_OK:               return "okay";
    case DP_ERR_NULL:         return "lacking argument";
    case DP_ERR_EMPTY:        return "empty enter";
    case DP_ERR_NOT_A_NUMBER: return "not a quantity";
    case DP_ERR_TRAILING:     return "additional characters after the quantity";
    case DP_ERR_RANGE:        return "quantity out of vary";
    case DP_ERR_TOO_LONG:     return "enter too lengthy";
    case DP_ERR_EOF:          return "finish of enter";
    case DP_ERR_OVERFLOW:     return "measurement overflow";
    case DP_ERR_NO_MEMORY:    return "out of reminiscence";
    case DP_ERR_IO:           return "enter/output error";
    }
    return "unknown error"; /* a price outdoors the enum */
}

An error code solely helps if the caller checks it. GCC and Clang can implement that: the DP_NODISCARD macro within the header provides __attribute__((warn_unused_result)), so this name doesn’t compile with -Werror:

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

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

One distinction issues: Clang helps you to silence the warning with a (void) solid, which paperwork a deliberate choice, however GCC nonetheless warns. C23 provides the usual [[nodiscard]] attribute; within the check run, GCC 13 and Clang 18 (with -std=c2x) each warned about an ignored outcome and each accepted a (void) solid.

Normal library capabilities report errors in their very own methods, and every wants its personal examine:

  • malloc, calloc, fopen, fgets return NULL.
  • fclose, fflush, fputs return EOF; fprintf returns a adverse quantity.
  • fwrite and fread return fewer gadgets than requested; use ferror to inform an error from finish of file.
  • errno says why, however solely proper after a name that failed. Reserve it earlier than calling the rest, because the take away name in dp_copy_file beneath does.

4. Assert Inner Assumptions

assert(situation) stops this system with the file, line and situation when the situation is fake. It’s for programmer errors: situations that can not be false if the code is right, corresponding to a pointer your personal perform ensures isn’t NULL or an index you may have already range-checked. It’s not for person errors, for 2 causes. A person ought to get an error message, not a crash. And assert disappears fully when NDEBUG is outlined, which most launch builds do.

That second level produces a basic bug when the asserted expression does actual work:

/* An assert whose situation does work. Constructed with NDEBUG (as launch builds
 * normally are), the entire expression disappears, and so does the work. */
#embody <assert.h>
#embody <stdio.h>

static int gadgets = 3;

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

int essential(void)
{
    assert(take_item()); /* WRONG: the decision vanishes when NDEBUG is outlined */
#ifdef NDEBUG
    printf("NDEBUG construct: %d gadgets leftn", gadgets);
#else
    printf("debug construct:  %d gadgets leftn", gadgets);
#endif
    return 0;
}

The check suite builds this file twice. The debug construct prints:

debug construct:  2 gadgets left

The construct with NDEBUG prints:

NDEBUG construct: 3 gadgets left

Within the launch construct the merchandise was by no means taken, as a result of the decision inside assert was eliminated with it. The repair is to do the work first and assert on the outcome: int okay = take_item(); assert(okay);.

5. Verify at Compile Time with static_assert

Some assumptions will be checked earlier than this system runs. C11’s static_assert (from <assert.h>) stops the compilation when a continuing expression is fake. It prices nothing at run time and can’t be turned off. Typical makes use of are the scale of a sort, the format of a construction written to a file and the connection between two constants. folks.c beneath makes use of one to tie a buffer measurement to its fixed.

A static assertion additionally catches surprises. This construction appears to be like like 7 bytes, however the compiler provides a byte of padding, so the assertion fails on GCC, Clang and MSVC alike:

/* Should not compile wherever: the static assertion paperwork the on-disk
 * measurement of a header, and padding makes the struct bigger than that. */
#embody <assert.h>
#embody <stdint.h>

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

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

int essential(void)
{
    return 0;
}
GCC 13:   error: static assertion failed: "header have to be 7 bytes on disk"
Clang 18: error: static assertion failed as a consequence of requirement 'sizeof(struct header) == 7': header have to be 7 bytes on disk

6. Move a Dimension with Each Buffer

Most buffer overflows in C come from a perform that writes to a buffer with out understanding its measurement: will get (faraway from the language in C11), strcpy, strcat and sprintf. The defensive rule is easy: each pointer to a buffer travels with its measurement, and each write checks it.

  • Use fgets as an alternative of will get and snprintf as an alternative of sprintf. Verify snprintf‘s return worth: a outcome higher than or equal to the buffer measurement means the output was minimize quick.
  • Watch out with strncpy: when the supply is just too lengthy, it does not add the terminating zero.
  • Write sizeof buffer the place the array is asserted, not a repeated quantity, and keep in mind that sizeof on a pointer parameter provides the scale of the pointer, not the array.

This copy perform all the time terminates the outcome and studies truncation, so the caller decides whether or not a shortened string is appropriate:

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

C11’s optionally available Annex Okay defines strcpy_s and comparable “secure” capabilities, however glibc and the opposite frequent C libraries on Linux and macOS don’t present them, and Microsoft’s variations differ from the usual, so moveable code normally writes small capabilities like this one.

7. Verify Dimension Arithmetic Earlier than Allocating

malloc(depend * measurement) has a hidden bug: if the multiplication overflows size_t, the outcome wraps round to a small quantity, malloc succeeds and this system writes far previous the tip of a small allocation. With depend coming from a file header or a community message, it is a basic safety gap. Verify 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 depend, size_t measurement, void **out)
{
    if (out == NULL) {
        return DP_ERR_NULL;
    }
    size_t bytes;
    const dp_status st = dp_mul_size(depend, measurement, &bytes);
    if (st != DP_OK) {
        return st;
    }
    void *p = calloc(depend == 0 ? 1 : depend, measurement == 0 ? 1 : measurement);
    if (p == NULL) {
        return DP_ERR_NO_MEMORY;
    }
    *out = p;
    return DP_OK;
}

Trendy C libraries make the identical examine inside calloc, however an express examine provides a transparent error code and works for realloc too, which has no such examine. C23 provides ckd_mul in <stdckdint.h> for a similar goal, and GCC and Clang supply __builtin_mul_overflow.

The identical care applies to signed arithmetic. Signed overflow is undefined habits in C, so complete += 1 with complete == INT_MAX is a bug even when it appears to work. Verify in opposition to INT_MAX earlier than including, or use a wider kind.

8. Launch Assets on Each Path

Error dealing with in C means returning early, and each early return should launch what the perform has acquired to date. The frequent C idiom is a single cleanup block on the finish of the perform, reached with goto. It retains the success path readable and makes it onerous to neglect one useful 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 standing = DP_ERR_IO;
    FILE *in = NULL;
    FILE *out = NULL;
    int created = 0; /* set as soon as 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;
    whereas ((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 final buffer, so its outcome issues too. */
    const int close_failed = fclose(out);
    out = NULL;
    if (close_failed != 0) {
        goto cleanup;
    }
    standing = DP_OK;

cleanup:
    if (in != NULL) {
        fclose(in);
    }
    if (out != NULL) {
        fclose(out);
    }
    if (standing != DP_OK && created) {
        const int saved = errno;
        take away(to_path); /* don't go away a half-written copy */
        errno = saved;
    }
    return standing;
}

4 particulars make this perform defensive reasonably than merely right:

  • The results of fclose is checked for the output file, as a result of fclose writes the final buffered knowledge and may fail on a full disk.
  • ferror(in) is checked after the learn loop, as a result of fread returns 0 for each finish of file and a learn error.
  • A failed copy deletes its partial output, so no half-written file is mistaken for a great one. The created flag ensures {that a} failure to open the enter by no means deletes an current file on the output path; a deliberate mistake within the check suite removes the flag, and the checks catch it.
  • errno is saved round take away, so the caller nonetheless sees why the copy failed.

9. Initialize Variables and Preserve State Constant

An uninitialized native variable holds no matter was in that reminiscence, and studying it’s undefined habits. Initialize variables the place you declare them, even whenever you consider each path units them. When GCC’s static analyzer (-fanalyzer) checked folks.c beneath, it couldn’t show that each path set a document earlier than it was printed, and reported a doable uninitialized learn. Initializing the document the place it’s declared prices nothing and eliminated the warning.

The identical precept applies to state that outlives a perform:

  • Write outputs solely on success, as each perform in defensive.h does, so a failed name 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 each change on an enum a path for sudden values, as dp_strerror does after its change.

10. Let the Compiler, Sanitizers and Analyzers Verify

Defensive code reduces bugs; instruments discover those that stay. Every of those applications within the pitfalls folder comprises one basic bug, and the desk exhibits what caught it within the check run:

Bug Regular construct Caught by
malloc(strlen(s)) then strcpy: one byte too few Ran, printed the appropriate textual content, exit standing 0 AddressSanitizer: heap-buffer-overflow
Studying reminiscence after free Not run (undefined habits) GCC 13 -Wall at compile time (-Wuse-after-free); AddressSanitizer: heap-use-after-free
INT_MAX + 1 Not run (undefined habits) UndefinedBehaviorSanitizer: signed integer overflow: 2147483647 + 1 can't be represented in kind 'int'
malloc, then an early return when fopen fails Ran usually GCC -fanalyzer with out working it: leak of 'buffer' [-Wanalyzer-malloc-leak]

The primary row is the essential one: the off-by-one program labored in a standard construct. Reminiscence bugs in C typically keep invisible till a unique enter, compiler or platform turns them right into a crash or a safety gap. That’s the reason the instruments belong in each construct, not solely in a disaster:

  • Warnings: compile with -Wall -Wextra -Wpedantic -Wconversion -Werror (GCC, Clang) or /W4 /WX (MSVC). -Wconversion finds silent narrowing corresponding to a size_t saved in an int.
  • Sanitizers: run the check suite with -fsanitize=handle,undefined on GCC and Clang, or /fsanitize=handle on MSVC. AddressSanitizer’s typical slowdown is 2x, which is ok for checks.
  • Static evaluation: GCC’s -fanalyzer, clang-tidy and MSVC’s /analyze discover bugs on paths that checks by no means execute, corresponding to error paths.
  • Valgrind finds leaks and invalid reads in an unmodified Linux construct.
  • Hardening for launch builds: -D_FORTIFY_SOURCE=3 and -fstack-protector-strong add low-cost run-time checks to manufacturing binaries.

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

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

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

Placing It Collectively: Validating a File of Information

folks.c reads title,age data and makes use of the library at each step: dp_read_line for lengthy strains, dp_parse_long for the age, a measurement examine for the title, a static_assert for the buffer and an error message with a line quantity for each rejected document:

/* folks: reads "title,age" strains, rejects unhealthy data with a purpose and a
 * line quantity, and prints the legitimate ones. Utilization: folks FILE */
#embody "defensive.h"

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

#outline NAME_MAX_LEN 32
#outline LINE_MAX_LEN 80

typedef struct {
    char title[NAME_MAX_LEN + 1];
    lengthy age;
} particular person;

/* Checked when compiling: parse_person depends on this. */
static_assert(sizeof(((particular person *)0)->title) == NAME_MAX_LEN + 1,
              "title should maintain NAME_MAX_LEN characters and the terminator");

/* Splits "title,age" and validates each fields.
 * Returns NULL on success, in any other case the explanation the document was rejected. */
static const char *parse_person(const char *line, particular person *out)
{
    if (line[0] == '') {
        return "empty line";
    }
    const char *comma = strchr(line, ',');
    if (comma == NULL) {
        return "lacking comma";
    }
    const size_t name_len = (size_t)(comma - line);
    if (name_len == 0) {
        return "empty title";
    }
    if (name_len > NAME_MAX_LEN) {
        return "title longer than 32 characters";
    }
    lengthy age;
    const dp_status st = dp_parse_long(comma + 1, 0, 150, &age);
    if (st != DP_OK) {
        return dp_strerror(st);
    }
    memcpy(out->title, line, name_len);
    out->title[name_len] = '';
    out->age = age;
    return NULL;
}

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

    char line[LINE_MAX_LEN + 1]; /* 80 characters and the terminator */
    unsigned lengthy quantity = 0;
    int accepted = 0;
    int rejected = 0;
    dp_status st;
    whereas ((st = dp_read_line(in, line, sizeof line)) != DP_ERR_EOF) {
        quantity++;
        particular person p = {{0}, 0}; /* initialized, so no path can print rubbish */
        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("okay    line %lu: %s, %ldn", quantity, p.title, p.age);
            accepted++;
            proceed;
        }
        printf("error line %lu: %sn", quantity, why);
        rejected++;
        if (st == DP_ERR_IO) {
            break;
        }
    }
    const int read_failed = ferror(in);
    fclose(in);
    printf("%d accepted, %d rejectedn", accepted, rejected);
    return (rejected == 0 && !read_failed) ? 0 : 1;
}

The check file comprises two legitimate data, each sort of unhealthy document this system checks for, a line with Home windows line endings and a final line and not using a newline. The output:

okay    line 1: Ada Lovelace, 36
okay    line 2: Alan Turing, 41
error line 3: empty line
error line 4: lacking comma
error line 5: empty title
error line 6: not a quantity
error line 7: additional characters after the quantity
error line 8: quantity out of vary
error line 9: quantity out of vary
error line 10: quantity out of vary
okay    line 11: Barbara Liskov, 86
error line 12: title longer than 32 characters
error line 13: line longer than 80 characters
okay    line 14: Edsger, 72
okay    line 15: Niklaus, 89
5 accepted, 10 rejected

Two particulars are price noticing. This system retains going after a nasty document and studies all of them, which is what a person fixing a file desires. And it returns exit standing 1 when any document was rejected, so a script that runs it may possibly inform that one thing was mistaken.

Defensive Programming in C++: What Adjustments

The identical strategies apply in C++, however the usual library takes over a lot of the bookkeeping. The repository features a C++ model of the library and of folks, and the C++ folks should print precisely the identical report because the C one: each check suites evaluate in opposition to the identical anticipated output file.

Approach C C++
Parse numbers strtol with errno and the tip pointer std::from_chars: no errno, no locale, by no means throws
Pressure callers to examine outcomes warn_unused_result (GCC, Clang) or C23 [[nodiscard]] [[nodiscard]], normal since C++17
Buffers and sizes A measurement handed with each pointer std::string, std::vector and std::string_view carry their measurement
Bounds checks Express if earlier than each index at() throws std::out_of_range
Launch sources goto cleanup RAII: destructors shut recordsdata and free reminiscence on each path
Errors with values Standing code plus an output pointer std::optionally available, or std::anticipated in C++23

The C++ parser is shorter as a result of std::from_chars studies each “no digits” and “out of vary” in its outcome. It doesn’t skip white area or settle for a number one +, so the perform handles each to match the C model:

Standing parse_long(std::string_view textual content, lengthy min, lengthy max, lengthy& out) noexcept
{
    const auto first = textual content.find_first_not_of(" tnvfr");
    if (first == std::string_view::npos) {
        return Standing::empty;
    }
    textual content.remove_prefix(first);
    if (textual content.measurement() > 1 && textual content[0] == '+' && textual content[1] != '-') {
        textual content.remove_prefix(1); // from_chars doesn't settle for a '+' signal
    }
    lengthy worth = 0;
    // from_chars by no means throws, ignores the locale and studies the place it stopped.
    const auto [end, error] = std::from_chars(textual content.knowledge(), textual content.knowledge() + textual content.measurement(), worth);
    if (error == std::errc::invalid_argument) {
        return Standing::not_a_number;
    }
    if (error == std::errc::result_out_of_range || worth < min || worth > max) {
        return Standing::vary;
    }
    if (finish != textual content.knowledge() + textual content.measurement()) {
        return Standing::trailing;
    }
    out = worth;
    return Standing::okay;
}

The file copy wants no cleanup block: the streams shut themselves after they exit of scope, on each return path. Two checks stay the programmer’s job, and each are straightforward to overlook in C++ too:

Standing copy_file(const std::string& from_path, const std::string& to_path)
{
    std::ifstream in(from_path, std::ios::binary);
    if (!in) {
        return Standing::io; // nothing created but, so nothing to scrub up
    }
    {
        std::ofstream out(to_path, std::ios::binary);
        if (!out) {
            return Standing::io;
        }
        char buffer[4096];
        whereas (in.learn(buffer, sizeof buffer) || in.gcount() > 0) {
            if (!out.write(buffer, in.gcount())) {
                break;
            }
        }
        const bool read_failed = in.unhealthy();
        out.shut(); // flush now, so a full disk is detected right here
        if (read_failed || out.fail()) {
            std::take away(to_path.c_str()); // don't go away a half-written copy
            return Standing::io;
        }
    } // the streams shut themselves on each path: no goto wanted
    return Standing::okay;
}
  • The output stream is closed explicitly earlier than the examine, so a write error throughout the last flush is seen.
  • The copy loop is express. The shorter out << in.rdbuf(); units the output stream’s failure flag when the enter file is empty, so an accurate copy of an empty file can be reported as an error. The unit checks copy an empty file to catch precisely this.

[[nodiscard]] can be extra helpful in C++ than its C counterpart: it’s a part of the usual, so the identical code that fails with GCC and Clang (error: ignoring return worth ... declared with attribute 'nodiscard') additionally fails on MSVC with /W4 /WX, which studies warning C4834.

Widespread Defensive Programming Errors

  • Utilizing assert to examine person enter. It crashes on unhealthy enter, and in a launch construct it doesn’t examine in any respect.
  • Placing work inside assert. The work disappears with NDEBUG, as proven above.
  • Checking errno and not using a failed name. errno retains its outdated worth on success, so set it to 0 first, as dp_parse_long does, or examine it solely after a failure.
  • Ignoring the results of fclose on a file you wrote. The final knowledge is written when the file is closed.
  • Hiding bugs with silent defaults. Returning 0 or an empty string when one thing inconceivable occurs retains this system working with mistaken knowledge. Return an error, or assert.
  • Checking the identical factor at each stage. Validate as soon as on the boundary, then belief the information inside; checks repeated in each perform make the code more durable to learn with out making it safer.

Incessantly Requested Questions

Key Takeaways

  • Validate every thing that enters this system on the belief boundary, and report errors to the caller.
  • Use strtol with errno and the tip pointer as an alternative of atoi, and check each side of each boundary.
  • Return standing codes, write outputs solely on success and use warn_unused_result or C23 [[nodiscard]] so callers can’t ignore them.
  • Use assert for bugs and by no means for person enter; by no means put work inside it.
  • Move a measurement with each buffer, and examine measurement arithmetic earlier than malloc.
  • Launch sources on each path with a single cleanup block, and examine fclose on recordsdata you write.
  • Run checks with warnings as errors, AddressSanitizer, UBSan and a static analyzer: the off-by-one bug on this information labored till a sanitizer stopped it.

Conclusion

Defensive programming in C comes down to at least one behavior: by no means let a price or a outcome go unchecked simply because it’s normally high quality. Validate enter as soon as, on the fringe of this system; examine each name that may fail; state your assumptions with assertions; and let the compiler and sanitizers search for the bugs that stay. None of those strategies is pricey, and collectively they flip silent reminiscence corruption into a transparent error message near its trigger. For a whole rule set, the SEI CERT C Coding Normal organizes its guidelines by subject, together with error dealing with, integers and strings.

The strategies construct on the basics of the language: secure enter and output in C for studying knowledge, malloc, calloc and free for checked allocation, and file dealing with in C for checking each file operation. For the larger query of when a program ought to cease and when it ought to keep on, see errors: to fail or to get better. Extra C tutorials are within the C programming part.

Supply Code and Assessments

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

The whole code is on GitHub:

Construct and check both model (CMake 3.20 or later; on Home windows, use a Developer PowerShell):

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

What the checks examine.

  • Unit checks: 72 checks of the library, together with each side of each buffer and vary boundary, NULL arguments and a failed file copy.
  • Program output: folks, the atoi comparability and each builds of the assert instance should print precisely the recorded output.
  • Code that should not compile: the ignored standing (GCC and Clang) and the failing static_assert (all compilers).
  • Instruments: the sanitizers should cease the three reminiscence bugs, and -fanalyzer should report the leak and nothing within the library.
  • C++ model: 53 unit checks, the shared folks output, the at() instance and the [[nodiscard]] compile-fail check.
  • Deliberate errors: 4 modifications to every library, every of which should make a check fail.

What I Verified

All outcomes come from run_all.sh (Linux) and run_all.ps1 (Home windows) within the two repositories, run for this text.

Verify Linux (Ubuntu 24.04) Home windows 11
Construct with warnings as errors GCC 13.3 and Clang 18.1, C11 and C17, -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Wformat=2 -Werror: handed MSVC 19.44, C11 and C17, /W4 /WX: handed
CTest: 72 unit checks, 4 output comparisons, 2 compile-fail checks Handed with each compilers and each requirements Handed with each requirements
AddressSanitizer and UBSan CTest handed; the off-by-one, the learn after free and INT_MAX + 1 have been every stopped MSVC /fsanitize=handle: CTest handed; the off-by-one (heap-buffer-overflow) and the learn after free (heap-use-after-free) have been stopped. MSVC has no UBSan
Valgrind memcheck (unit checks and folks) No errors, no leaks Not relevant
GCC -fanalyzer Reported the leak in leak_on_error.c; nothing in defensive.c or folks.c Not relevant
Deliberate errors {that a} check should catch 4 of 4 caught 4 of 4 caught
C++ model: construct and CTest (53 unit checks, shared folks output, at(), [[nodiscard]] compile-fail) GCC 13.3 and Clang 18.1, C++17 and C++20, warnings as errors: handed; ASan, UBSan and Valgrind clear MSVC 19.44, C++17 and C++20, /W4 /WX: handed, together with the [[nodiscard]] compile-fail check
C++ model: deliberate errors 4 of 4 caught 4 of 4 caught

Not coated: C23 compilers in C23 mode (solely the [[nodiscard]] examine used -std=c2x), MSVC’s /analyze or platforms aside from x86-64.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments