Secure Coding in C · intermediate · ~10 min

Safe string functions

Choose the right replacement for each unsafe one.

Lesson

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.