Secure Coding in C · intermediate · ~10 min
Choose the right replacement for each unsafe one.
| Unsafe | Safer drop-in |
|---|---|
strcpy |
snprintf(dst, sz, "%s", src) (or check length first) |
strcat |
snprintf(dst+len, sz-len, "%s", more) |
sprintf |
snprintf and check return |
gets |
fgets(buf, sz, stdin) |
strtok |
strtok_r (re-entrant) |
Some platforms also offer strlcpy/strlcat (BSD; not in standard C) which always NUL-terminate and report needed length.