Coding

strcpy in C: Syntax, Dangers and Safer Alternatives

strcpy in C copies the string at src, including its terminating null byte, into the buffer at dest, and returns dest. It never checks how big dest is, so a source that is too long overflows the buffer; for untrusted or variable-length input, use snprintf and check its return value.

strcpy syntax

The declaration lives in <string.h>:

char *strcpy(char *restrict dst, const char *restrict src);

It copies characters from src up to and including the first '\0', then returns the pointer it was given as the destination. A minimal correct use looks like this:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char name[16];
    strcpy(name, "Alex");
    printf("%s\n", name);
    return 0;
}

This is safe only because the programmer can see that "Alex" needs 5 bytes (four letters plus the null byte) and name has 16. The function itself has no way to know that. The Linux man page states that the programmer is responsible for allocating a destination buffer large enough, and that if it is too small the behavior is undefined.

The rules strcpy relies on

According to cppreference, the behavior of strcpy is undefined if any of these holds:

  • dest is not large enough to hold src including its null terminator.
  • The source and destination strings overlap.
  • src is not a null-terminated byte string, or dest is not a pointer to a character array.

The first rule is the famous one. The third is easy to miss: if src is a character array that was filled without a terminator, strcpy keeps reading past its end until it happens to find a zero byte. For overlapping memory, the man page says the strings may not overlap. If you need to move bytes within the same buffer, see memcpy in C and the memmove difference.

How a buffer overflow happens

The size of the destination is a property of the array, not of the pointer you pass. Inside a function, an array parameter becomes a plain pointer, so sizeof no longer reports the array size (see arrays in C). That is why code like this is dangerous:

void set_name(char *dest, const char *input)
{
    strcpy(dest, input);   /* no idea how big dest is */
}

char name[8];
set_name(name, "Alexandria");   /* needs 11 bytes, buffer has 8 */

The copy writes 3 bytes past the end of name. The C standard calls that undefined behavior: the program may appear to work, crash, or overwrite neighboring data. Which one you get can change between compilers, optimization levels and runs, so a test that passes proves nothing.

The man page points to _FORTIFY_SOURCE (documented in feature_test_macros(7)) as a safeguard on Linux with glibc. That is a compile-time hardening option that helps catch some overflows; it is a safety net, not a substitute for correct sizes.

Safer alternative 1: snprintf

For copying a string into a fixed-size array, snprintf is the most practical standard option. Per cppreference, at most bufsz - 1 characters are written and the result is null-terminated, unless bufsz is zero.

char name[8];
int needed = snprintf(name, sizeof name, "%s", "Alexandria");

if (needed < 0) {
    /* encoding error */
} else if ((size_t)needed >= sizeof name) {
    /* output was truncated: name holds "Alexand" */
}

The return value is the number of characters the full output would have had, not the number stored. If it is greater than or equal to the buffer size, the text was cut off. A negative value means an encoding error. Always use "%s" as the format and pass the source as an argument; passing the source as the format string itself lets any % in the data be interpreted as a conversion.

Because sizeof name only works where name is an actual array, pass the size explicitly when you write a helper function that takes a pointer.

Safer alternative 2: strncpy, with a manual terminator

strncpy looks like the bounded version of strcpy, but it has two traps. From cppreference:

  • If the source is count characters or longer, the result is not null-terminated.
  • If the source is shorter, the remaining bytes up to count are filled with null characters. A large buffer and a short string therefore costs a full count bytes of writing.

The usual pattern reserves one byte and terminates explicitly:

char dst[16];
strncpy(dst, src, sizeof dst - 1);
dst[sizeof dst - 1] = '\0';

This never overflows dst and always leaves a valid string, but it truncates silently and reports nothing. If you need to know about truncation, snprintf is the better fit. Forgetting the last line is the classic bug, and it turns a missing terminator into a later out-of-bounds read.

Safer alternative 3: strcpy_s (Annex K)

C11 added an optional bounds-checking interface. Its signature is:

errno_t strcpy_s(char *restrict dest, rsize_t destsz, const char *restrict src);

It returns zero on success and non-zero on error. On a runtime constraint violation (null pointer, a zero or oversized destsz, truncation, or overlap) it calls the installed constraint handler and, in most cases, writes a zero to dest[0] so the result is an empty string. Cppreference notes it does not silently truncate; to truncate on purpose you use strncpy_s.

The catch is availability. It exists only if the implementation defines __STDC_LIB_EXT1__, and your code must define __STDC_WANT_LIB_EXT1__ to 1 before including <string.h>. Because it is optional, code that must build on several platforms cannot assume it. Check your toolchain's documentation before relying on it.

Safer alternative 4: measure first, then memcpy

When you control the allocation, you can size the buffer from the source. This is a normal pattern for duplicating a string:

size_t length = strlen(src);
char *copy = malloc(length + 1);   /* +1 for the null byte */
if (copy == NULL) {
    /* handle allocation failure */
}
else {
    memcpy(copy, src, length + 1);
}

Here the size of the destination is derived from the source, so the copy cannot overflow. Remember that every malloc needs a matching free (see malloc in C).

Which one to use

SituationUseWatch out for
Fixed array, input length unknownsnprintf(dst, sizeof dst, "%s", src)Check the return value for truncation
Fixed array, silent truncation is finestrncpy plus manual terminatorForgetting the terminator; zero padding cost
Dynamic allocationstrlen, malloc(length + 1), memcpyCheck for NULL, free later
Platform provides Annex Kstrcpy_sOptional, not portable
Source length proven smaller than destinationstrcpyThe proof must survive future edits

Reading input safely before copying

Most overflows start when text arrives from a user, a file or the network. If you read a line with fgets, the size limit is already applied at the read, and you can often skip the copy entirely. See fgets in C for how it handles the newline and long lines.

Checklist before you call strcpy

  • Can you point to the line that guarantees the source length plus one is at most the destination size?
  • Is the source definitely null-terminated?
  • Do the two buffers definitely not overlap?
  • Would that guarantee still hold if someone changes the buffer size or the input later?

If any answer is "I think so", switch to snprintf. It costs one extra argument and turns a silent memory bug into a result you can test.

Frequently asked questions

What does strcpy do in C?
strcpy copies the string at src, including its terminating null byte, into the buffer at dest, and returns dest. It does not check the size of dest, so the caller must make sure the buffer holds the source length plus one byte.
Is strcpy deprecated?
strcpy is still part of the C standard library and is not removed. It is unsafe by design because it never checks the destination size, so many coding standards and code reviews avoid it for any input whose length you do not control.
Is strncpy a safe replacement for strcpy?
Not by itself. If the source is count characters or longer, strncpy does not write a null terminator, and it pads short copies with zeros up to count bytes. You must terminate the buffer yourself, or use snprintf instead.
What is strcpy_s?
strcpy_s is the bounds-checking version from the optional Annex K of C11. It takes the destination size and calls a constraint handler on truncation or overlap. It is available only if the implementation defines __STDC_LIB_EXT1__, and many common compilers and libraries do not provide it.
How do I copy a string in C without strcpy?
Use snprintf(dest, sizeof dest, "%s", src) when dest is an array, then check the return value for truncation. For a known-length copy where you have verified the size, memcpy with length plus one also works.

Sources