Safe String Practices in C
Most C security disasters are string disasters, and all share one root cause: writing past a buffer nobody measured. The safe discipline has four habits — always know destination capacity, prefer bounded functions (strncpy, strncat, snprintf), guarantee termination yourself (strncpy may leave strings unterminated!), and ban gets() entirely (removed from C11 for being unfixably unsafe).
snprintf(dst, sizeof dst, ...) is the crown jewel: one call that formats, bounds, and always terminates. For dynamic text, measure with strlen, malloc(len + 1), then copy — the allocate-exactly pattern that never overflows.
Know every capacity
Track each buffer's size at declaration; every copy/append/concatenation checks against it before writing.
snprintf for formatting
snprintf(dst, sizeof dst, "%s=%d", k, v); bounds and terminates in one call — the safest formatter available.
strncpy's termination trap
strncpy pads but may skip the terminator when source fills the buffer — always follow with dst[size-1] = 0.
Allocate exactly
char *d = malloc(strlen(s) + 1); strcpy(d, s); — the +1 is the terminator, and forgetting it is the classic off-by-one.
#include <stdio.h>#include <string.h> int main(void) { char buf[8]; snprintf(buf, sizeof buf, "%s-%d", "id", 42); printf("%s\n", buf); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.