Learn C
#include "arraysstrings/string_safety.h"

Safe String Practices in C

#concept

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.

#how it works
1

Know every capacity

Track each buffer's size at declaration; every copy/append/concatenation checks against it before writing.

2

snprintf for formatting

snprintf(dst, sizeof dst, "%s=%d", k, v); bounds and terminates in one call — the safest formatter available.

3

strncpy's termination trap

strncpy pads but may skip the terminator when source fills the buffer — always follow with dst[size-1] = 0.

4

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.

#example
#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;
}
Output
id-42
1snprintf receives the full 8-byte capacity and formats within it — id-42 fits with room to spare.
2Had the text exceeded 7 characters, snprintf would truncate and still terminate — never overflow.
3id-42 prints complete, proving bounded formatting composes safely.
#use cases
Replacing every sprintf with snprintf(dst, sizeof dst, ...)
Terminating manually after strncpy when sources may fill buffers
Allocating strlen + 1 for every dynamic string copy
Banning gets() on sight in any code under review

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.