← Strings and ArraysC PROGRAMMING 1.3.D
String Library Functions
strlen/strcpy/strcmp and friends, and their sharp edges.
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.
| Function | Does | Sharp edge |
|---|---|---|
strlen(s) | counts bytes up to (not including) \0 | no bounds check — reads forever if \0 is missing |
strcpy(dst, src) | copies including the terminator | no length limit — classic buffer overflow if dst is too small |
strncpy(dst, src, n) | copies at most n bytes | doesn't null-terminate dst if src is n bytes or longer — has to be done manually |
strcmp(a, b) | lexicographic compare | returns 0 for equal — easy to misread as a boolean "true means equal" |
strcat(dst, src) | appends src onto dst | same 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