C Programming • C17 baseline, standards-specific features labeled
Secure C: Bounds, Ownership, and Input Boundaries
Treat external data as untrusted and make buffer sizes, ownership, and failure paths explicit.
Many C defects arise when lengths, lifetimes, or input assumptions are implicit. Validate sizes before allocation, check every conversion, avoid unbounded string operations, and define who owns each resource. Sanitizers and static analysis help find defects but do not replace review.
Example
#include <stdio.h>
int format_label(char *destination, size_t capacity, unsigned id) {
if (destination == NULL || capacity == 0) {
return 0;
}
int written = snprintf(destination, capacity, "record-%u", id);
return written >= 0 && (size_t)written < capacity;
}
What to expect
The function reports failure if the destination cannot hold the full label and its terminator.
Key idea: Security comes from consistent contracts across parsing, allocation, indexing, formatting, and cleanup.