Arrays & Strings · beginner · ~10 min
See why strcpy is unsafe and what to use instead.
strcpy(dst, src) copies bytes from src to dst until and including the NUL — and it never checks how big dst is. If src is longer than dst's buffer, it overflows. This single function is responsible for thousands of CVEs over the years.
Use snprintf(dst, size, "%s", src) or strncpy (with explicit termination) instead. Better: track destination buffer sizes everywhere and use bounded operations.
// UNSAFE
char dst[8];
strcpy(dst, "this is way too long"); // overflows by 13 bytes
// Safe
char dst[8];
snprintf(dst, sizeof dst, "%s", src); // always NUL-terminates, truncates
strncpy does NOT always NUL-terminate when src is longer than n — always set dst[n-1] = 0 afterwards.