YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Correctness & careChapter 63 of 73

Defensive C and security boundaries

Validate sizes and meanings, preserve buffer contracts, keep formats trusted, and understand what hardening can and cannot establish.

6 min readIntermediateC17 baseline
Offline reading
In this chapter8 sections

A program must decide which inputs and resource requests it will accept. Bounds checks, size calculations, and trust boundaries help make that decision explicit. Defensive code needs a clear model of the resources and regions it is protecting.

1. Validate meaning as well as storage limits

A bounded string can still name an unauthorized file or request an invalid state transition. A valid integer can still exceed the application’s quota. Length checks, syntax checks, authorization, and resource limits answer different questions. Keep external data separate from control instructions such as format strings or command languages, and choose interfaces whose contracts are small enough to review.

2. Prove the allocation arithmetic before computing it

Complete C17 program
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>

static bool storage_size(size_t count, size_t element_size, size_t extra, size_t *result)
{
    if (result == NULL) return false;
    if (element_size != 0 && count > (SIZE_MAX - extra) / element_size) return false;
    *result = count * element_size + extra;
    return true;
}

int main(void)
{
    size_t result = 99;
    bool accepted = storage_size(3, 4, 2, &result);
    assert(accepted && result == 14);
    bool rejected = storage_size(SIZE_MAX, 2, 1, &result);
    assert(!rejected && result == 14);
    bool empty = storage_size(0, 4, 2, &result);
    assert(empty && result == 2);
    bool zero_element = storage_size(SIZE_MAX, 0, 2, &result);
    assert(zero_element && result == 2);
    return 0;
}

The comparison guards both multiplication and addition. Because extra is size_t, SIZE_MAX - extra is representable; division avoids first computing an overflowing product. A zero element size is handled without division by zero. The helper reports a size only, not permission to allocate or access an object. A caller must still enforce a meaningful count, a zero-size policy, failure handling, and the intended type/alignment contract.

Unsigned wrap is defined but can turn a huge request into a small allocation. Signed overflow is undefined. Converting a negative count to size_t before validation can turn it into a huge positive value. Validate the original domain, then prove the conversion and each arithmetic step rather than checking only the final wrapped result.

3. Make a buffer operation’s full contract visible

Complete C17 program
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>

/* Source has length readable bytes; destination has capacity writable bytes. */
static bool copy_label(char *destination, size_t capacity, const char *source, size_t length)
{
    if (destination == NULL || source == NULL || length >= capacity) return false;
    if (memchr(source, '\0', length) != NULL) return false;
    memmove(destination, source, length);
    destination[length] = '\0';
    return true;
}

int main(void)
{
    char label[5] = "old";
    bool rejected = copy_label(label, sizeof label, "longer", 6);
    assert(!rejected && strcmp(label, "old") == 0);
    bool accepted = copy_label(label, sizeof label, "new", 3);
    assert(accepted && strcmp(label, "new") == 0);
    const char embedded[] = { 'a', '\0', 'b' };
    bool nul_rejected = copy_label(label, sizeof label, embedded, sizeof embedded);
    assert(!nul_rejected && strcmp(label, "new") == 0);
    char overlap[8] = "coded";
    bool moved = copy_label(overlap, sizeof overlap, overlap + 2, 3);
    assert(moved && strcmp(overlap, "ded") == 0);
    return 0;
}

This interface accepts an explicit readable source length, rejects input NUL, reserves a terminator, and permits valid overlapping regions through memmove. It leaves the destination unchanged on rejection. The capacity check also proves length + 1 fits, without needing to compute that sum first. A non-null argument does not establish the claimed readable/writable regions; the caller still supplies those live objects.

A function name containing “n” or “safe” is not a universal guarantee. memcpy requires valid nonoverlapping regions; strncpy does not always terminate its destination; fgets may return only a chunk. Read the exact contract and the return value. Do not use strlen to discover the length of storage that has not already been established as a terminated string.

4. Treat a format string as executable instructions

Complete C17 program
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char *label = "progress 100%";
    if (printf("%s\n", label) < 0) return EXIT_FAILURE;
    return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}

The fixed format controls the conversion, while label remains data. Passing an untrusted string as the format can request missing or wrongly typed arguments and cause undefined behavior; consequences can include disclosure or unintended writes on particular implementations. It is not a guaranteed arbitrary-memory capability on every platform. Keep a fixed format or use an appropriate plain-text output function.

5. Hardening supports the design; it does not replace it

Compiler warnings, stack protection, sanitizer builds, static analysis, reviews, and tests add independent ways to catch mistakes. They do not make invalid pointer accesses or unchecked arithmetic correct. C provides automatic storage duration for suitable objects, but dynamically allocated memory has explicit ownership/release duties and ordinary array accesses have no required automatic bounds check. Avoid reducing that model to “C manages no memory at all.”

Protect secrets in diagnostics and define behavior when a limit is exceeded. Standard rand is not a cryptographic randomness interface; secure key generation, authenticated communication, and platform permissions require suitable dedicated facilities. This lesson develops memory/input boundaries, not a complete application-security or cryptographic protocol design.

Primary references and further reading

Before you move on

  • Validation includes semantic domains, resource limits, and checked size arithmetic.
  • Pointer and count contracts still require genuinely accessible regions.
  • Defensive choices reduce specified risks while remaining dependent on a clear threat and ownership model.
Keep these ideas separate
Non-null pointer / Valid region
A non-null value alone does not prove sufficient accessible storage, lifetime, alignment, or permission.
Explain it in your own words

Which checks belong before calculating and allocating space for an input-controlled number of elements?

Optional: say it aloud or keep a note. You can continue whenever you are ready.

Check your understanding

Optional. Answers are not saved or sent, and reading stays unrestricted.

What should happen before copying externally supplied data into a bounded buffer?
Read the explanation for every choice
  1. Trust a claimed length without checking capacity.

    A supplied length is input too; it can violate the receiving buffer’s bounds.

  2. Rename the buffer to make the operation safe.

    Names can communicate intent but cannot enforce a valid copy.

  3. Validate the length, capacity, and arithmetic needed by the copy contract.

    ✓ Correct reasoning. If a C string is required, account for its terminator as part of that contract.

C17

Quick reference from the earlier edition

Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.

Because ISO C generally leaves runtime bounds checks and the release of dynamically allocated memory to the program, a large share of historically significant software vulnerabilities trace back to a handful of recurring mistakes:

  • Buffer overflows. Writing past the end of a fixed-size array — classically a char buffer via strcpy or the now-removed gets — can corrupt adjacent memory, including, on the stack, a function's saved return address, which is the basis of "stack smashing" exploits.
  • Format string vulnerabilities. Passing untrusted input directly as a printf-family format string (printf(userInput) instead of printf("%s", userInput)) can cause conversions to use missing or inappropriate arguments, which has undefined behavior. Depending on the implementation and defenses, this can enable information disclosure or memory writes.
  • Integer overflow. Signed overflow is undefined behavior, and unsigned overflow silently wraps around — either of which can produce an unexpectedly small size value that then leads to an undersized buffer being allocated.
  • Mitigations. Prefer bounds-aware functions (snprintf over sprintf, fgets over gets), always pass a literal or validated format string, validate lengths before any arithmetic that feeds into an allocation size, and compile with stack-protection and warning flags enabled (Section 32).

Ready for the next idea?

Mark this chapter as read whenever you feel ready.

CHAPTER 63 / 73

In this chapter

Defensive C and security boundaries

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping