5.1.21 · D3C Programming

Worked examples — Safe alternatives — strncpy, snprintf, strlcpy

2,468 words11 min readBack to topic
Figure — Safe alternatives — strncpy, snprintf, strlcpy

The scenario matrix

Every case a copy function can hit is one of these cells. Each column is a length relationship between the source text and the destination capacity ; each degenerate row is an edge input.

Cell Situation What must happen Which example
A src shorter than copies fully + terminates; spare room Ex 1
B src length exactly just fits, terminates, no truncation Ex 2
C src length exactly the trapstrncpy drops the knot Ex 3
D src much longer than truncation, detect it Ex 4
E src empty ("") writes only '\0' Ex 5
F size = 0 passed function must touch nothing Ex 6
G real-world: build a path, detect overflow snprintf + return check Ex 7
H exam twist: chained copies, off-by-one reason about the knot Ex 8

We use char buf[8] () almost everywhere, so index is the last box and is our content cap.


Ex 1 — Cell A: short source, room to spare


Ex 2 — Cell B: source length exactly


Ex 3 — Cell C: source length exactly (THE TRAP)

Figure — Safe alternatives — strncpy, snprintf, strlcpy

Ex 4 — Cell D: source much longer, compare all three functions


Ex 5 — Cell E: empty source


Ex 6 — Cell F: the size = 0 edge


Ex 7 — Cell G: real-world path join with overflow detection


Ex 8 — Cell H: exam twist, chained copies and the off-by-one


Cell coverage check

Ex 1

Ex 2

Ex 3

Ex 4

Ex 5

Ex 6

Ex 7

Ex 8

scenario matrix

A short src

B exact C-1

C exact C trap

D oversized

E empty src

F size zero

G real path

H exam chain

all cells covered

Recall One-line summary of every cell

Short src pads safely; exact-C-1 fits and terminates; exact-C is the trap (strncpy drops the knot); oversized truncates (detect with r >= size); empty writes just a knot; size=0 touches nothing; real code compares the return against capacity; and a short source re-copy zero-fills away old garbage.

Which cell is the one that silently produces an unterminated string?
Cell C — source length exactly equals capacity , so strncpy copies all bytes and adds no '\0'.
In Ex 7, why does the guard r >= sizeof(path) NOT fire?
The intended text is 15 chars needing 16 bytes, capacity is 16, so it fits exactly; r == 15 and 15 >= 16 is false.
In Ex 8, why does line 3 restore termination without a manual fix?
"ab" is shorter than n, so strncpy pads boxes 2–4 with '\0', cleaning up and terminating automatically.

Connections

  • Parent · Safe alternatives
  • C strings and the null terminator
  • Buffer overflow and stack smashing
  • strcpy and sprintf (unsafe)
  • sizeof vs strlen
  • Format strings and printf family
  • Memory safety and undefined behavior