← Strings and ArraysC PROGRAMMING 1.3.D

String Library Functions

strlen/strcpy/strcmp and friends, and their sharp edges.

StatusCollected

Six pieces on <string.h> — the functions I'd used for years without ever reading the fine print on what happens when things go wrong.

FunctionDoesSharp edge
strlen(s)counts bytes up to (not including) \0no bounds check — reads forever if \0 is missing
strcpy(dst, src)copies including the terminatorno length limit — classic buffer overflow if dst is too small
strncpy(dst, src, n)copies at most n bytesdoesn't null-terminate dst if src is n bytes or longer — has to be done manually
strcmp(a, b)lexicographic comparereturns 0 for equal — easy to misread as a boolean "true means equal"
strcat(dst, src)appends src onto dstsame overflow risk as strcpy, plus has to walk dst first to find where to start

strncpy is the one that actually surprised me — it looks like the "safe" bounded version of strcpy, but if the source is exactly n bytes or longer it silently leaves the destination without a terminator at all, which just moves the bug somewhere less obvious instead of fixing it.

Notes from readers

Comments — via GitHub