Secure Coding in C · intermediate · ~10 min

Bounds checking everywhere

Adopt the discipline of capacity arguments.

Lesson

Bounds checking in C is manual. Every function that writes to a buffer needs the buffer's capacity, and must compare against it before writing. Conventional API shapes:

  • int copy_into(char *dst, size_t cap, const char *src) returning 0/-1.
  • Always reserving one byte for the NUL terminator in C strings.

Code examples

int safe_join(char *out, size_t cap, const char *a, const char *b) {
    int n = snprintf(out, cap, "%s/%s", a, b);
    return (n < 0 || (size_t)n >= cap) ? -1 : 0;
}