What is the difference between strcpy, strncpy and memcpy?
Short answer: strcpy(d, s) copies a string including its '\0' with no bounds check. strncpy(d, s, n) copies at most n characters and pads the rest with zeros, but does not add a terminator if the source is n characters or longer. memcpy(d, s, n) copies exactly n bytes regardless of content, and is undefined if the buffers overlap (use memmove then).
char dst[8];
strcpy(dst, "this is too long"); /* buffer overflow: writes past dst */
strncpy(dst, "abcdefgh", sizeof dst); /* copies 8 chars, NO '\0': dst is not a string */
dst[sizeof dst - 1] = '\0'; /* you must terminate it yourself */
memcpy(dst, src, 8); /* exactly 8 bytes; overlapping src/dst is UB */
memmove(buf + 1, buf, 7); /* overlapping: use memmove */
Stops at '\0' |
Bounds | Terminates | Pads | Overlap | |
|---|---|---|---|---|---|
strcpy |
yes | none | yes | no | UB |
strncpy |
yes (then pads) | n | only if strlen(s) < n |
with zeros up to n | UB |
memcpy |
no | n | not applicable | no | UB |
memmove |
no | n | not applicable | no | safe |
Why strncpy exists: it was designed for fixed-width, zero-padded fields (old Unix directory entries), not as a "safe strcpy". Padding a 4 KB buffer when copying a short string is also wasted time.
Safer patterns
snprintf(dst, sizeof dst, "%s", src); /* always terminates, truncates safely */
size_t n = strlen(src); /* or a bounded strnlen */
if (n >= sizeof dst) n = sizeof dst - 1;
memcpy(dst, src, n);
dst[n] = '\0';
strlcpy (BSD, glibc 2.38+, and many embedded libraries) copies, always terminates, and returns the source length so you can detect truncation. C11 Annex K strcpy_s exists but is rarely implemented.
Embedded note: these functions are a frequent source of overflows when parsing input from a UART or network. Always know the size of the destination, and prefer length-carrying buffers (ptr + len) over relying on '\0' in binary protocols.