
Choosing a Safe, Portable String Copy Function in C

Copying a C string looks simple until the source is longer than the destination, the result is not null-terminated, or code needs to build on several operating systems. The right choice depends on what you need: a plain copy, a fixed-width field, or a bounded copy whose result you can check. This guide compares strcpy, strncpy, strlcpy, and snprintf, with examples and portability details.
String-copying functions at a glance
| Function | What it copies | Null termination | Availability |
|---|---|---|---|
strcpy(dest, src) |
All of src, including its terminator |
Yes, if the copy completes | Standard C |
strncpy(dest, src, n) |
Up to n characters; pads with null bytes when source is shorter |
Not guaranteed when source length is at least n |
Standard C |
strlcpy(dest, src, size) |
At most size - 1 characters |
Yes, when size is greater than zero |
Common, but not standard C |
snprintf(dest, size, "%s", src) |
Formatted output, bounded by the destination size | Yes, when size is greater than zero |
Standard C99 and later |
None of these functions can determine whether a pointer is valid or whether a destination really has the size its code claims. The caller must provide valid pointers and the correct capacity. For overlapping source and destination regions, use memmove rather than treating a string-copy function as an overlap-safe operation. See memcpy vs memmove for the distinction, and best practices for memcpy in C.
How strcpy works—and where it can fail
The standard C function strcpy copies the source string, including its terminating null character, to the destination:
#include <string.h>
char *strcpy(char *dest, const char *src);
It does not accept a destination capacity. The destination must have room for every source character plus the terminating '\0'. If it does not, the function writes outside the array, causing undefined behavior that can include corrupted data, a crash, or a security vulnerability. This is a common route to buffer overflows.
char dest[6];
strcpy(dest, "Hello"); /* Fits: five characters plus '\0'. */
That example is valid because the destination capacity is known and sufficient. This one is not:
char dest[5];
strcpy(dest, "Hello"); /* Undefined behavior: no room for '\0'. */
strcpy can be appropriate when the destination size has already been proven sufficient—for example, when allocating exactly strlen(src) + 1 bytes. It is not automatically safe just because the input is trusted. Its safety depends on a correct capacity guarantee.
strncpy: bounded copying, but not a drop-in safe strcpy
strncpy copies at most n characters. If the source is shorter than n, it fills the rest of the destination with null bytes. If the source has n or more characters, it copies only n characters and does not append a terminator.
#include <string.h>
char *strncpy(char *dest, const char *src, size_t n);
This behavior is useful for creating null-padded, fixed-width character fields. It can be surprising when the goal is to produce an ordinary C string. A truncated result may not end in '\0', and padding a large destination can add unnecessary work.
For a destination array whose capacity is greater than zero, reserve one byte for the terminator and add it explicitly:
char dest[10];
strncpy(dest, "a longer message", sizeof dest - 1);
dest[sizeof dest - 1] = '\0';
This ensures termination, but it does not tell you whether truncation occurred. Compare the source length with the available capacity if that matters. Also, do not use strncpy when the intended format is a regular string and you have not considered its padding and termination rules.
strlcpy: useful semantics, nonstandard availability
strlcpy was developed by OpenBSD as a bounded string-copy interface. It copies at most size - 1 bytes from the source, then writes a terminator when size is nonzero. It returns the length of the entire source string, not the number of characters copied.
size_t strlcpy(char *dest, const char *src, size_t size);
That return value makes truncation straightforward to detect: if the returned source length is greater than or equal to the destination capacity, the complete string did not fit. A zero capacity means no destination bytes are written; the source is still measured.
char dest[8];
size_t needed = strlcpy(dest, "Hello, world", sizeof dest);
if (needed >= sizeof dest) {
/* The source was truncated. */
}
After the call, dest contains a terminated, truncated string. The return value is the source length—12 for "Hello, world"—so the comparison detects that the 8-byte destination could not hold the full string and its terminator.
Is strlcpy portable?
strlcpy is not part of ISO C, including C23, and is not guaranteed by POSIX. It is available on OpenBSD and several other systems, but support depends on the platform and its library version. Do not assume that including <string.h> makes it available everywhere.
If you use it, check the target platforms and their documentation, or provide a carefully reviewed compatibility implementation. Avoid defining a replacement with the same name as a system function without checking for existing declarations and feature-test requirements. For code that must compile across standard C implementations, use a portable alternative such as snprintf or a small helper with explicit capacity and truncation handling.
Using snprintf for bounded string output
snprintf is a standard C function for writing formatted output into a buffer with a specified capacity. It is available in C99 and later. For a plain string copy, use the %s conversion:
#include <stdio.h>
char dest[16];
int result = snprintf(dest, sizeof dest, "%s", "A sample string");
if (result < 0) {
/* An encoding or output error occurred. */
} else if ((size_t)result >= sizeof dest) {
/* Output was truncated. */
}
When the capacity is greater than zero, snprintf writes a terminating null character. Its return value is the number of characters that would have been written, excluding that terminator. A negative return value indicates an error; a nonnegative result greater than or equal to the capacity indicates truncation.
For a simple copy, snprintf may be less direct than a dedicated helper. It is especially useful when combining text or formatting values, but format strings must be handled carefully. For example, use a literal format string as above; do not pass untrusted input as the format string. If the source and destination overlap, behavior is undefined.
Choosing between strcpy, strncpy, strlcpy, and snprintf
The best choice depends on the required behavior and the platforms you support—not on a blanket claim that one function is always fastest or safest.
- Use
strcpyonly when you can prove the destination has enough space for the whole source and its terminator. - Use
strncpywhen you specifically need its null-padding behavior, such as for a fixed-width field. If using it to build a C string, handle termination and truncation deliberately. - Use
strlcpywhen it is available in your target environment and its return-value convention suits your code. Check the result to detect truncation. - Use
snprintffor portable, bounded formatted output or when a standard C interface is required. Check for both errors and truncation.
Do not choose based on assumed performance rankings. The work each function performs depends on the input, destination capacity, implementation, and compiler. Measure performance in the actual program if it is important.
Practical checks that prevent copy bugs
- Track destination capacity alongside the pointer; a pointer alone does not reveal an array’s size.
- Include space for the terminating null character when calculating string capacity.
- Check return values when truncation or output errors matter.
- Do not assume a bounded function can validate invalid pointers or an incorrect size argument.
- Use
memmovefor overlapping memory regions, notstrcpy,strncpy,strlcpy, orsnprintf.
Conclusion
strcpy is simple, but it relies entirely on the caller to ensure the destination is large enough. strncpy has different semantics from a typical safe string copy: it may omit the terminator and pads shorter inputs. strlcpy offers convenient bounded-copy behavior and useful truncation reporting, but it is not standard C or universally available. For portable bounded output, snprintf is a practical standard option when used with a correct capacity and checked return value. Understand the function’s exact behavior, verify available space, and make truncation an explicit decision.