Replace strcpy and sprintf With Safer Alternatives
Replace strcpy, strcat and sprintf in C with snprintf, memcpy with a checked length, and strlcpy, and detect truncation instead of overflowing a buffer.

strcpy, strcat and sprintf all share one flaw: they write until the source ends and never learn how big the destination is. Replacing them is the cheapest security fix in a C codebase, and it is mostly mechanical. This post walks through the replacement for each function, shows how to detect truncation instead of hiding it, and ends with a pattern for building a string piece by piece. Examples target GCC 15 on Linux 6.12 with glibc 2.41.
The three offenders
| Function | Unbounded because | Replacement |
|---|---|---|
strcpy(dst, src) | copies until src ends | snprintf or memcpy with a checked length |
strcat(dst, src) | appends until src ends, after scanning dst | snprintf at an offset, or memcpy |
sprintf(dst, fmt, ...) | output length depends on the arguments | snprintf(dst, sizeof dst, fmt, ...) |
gets is a fourth, but it was removed from the language in C11, so use fgets and move on. Two others to treat the same way are vsprintf, which has the bounded twin vsnprintf, and scanf("%s"), which needs an explicit width such as %63s.
snprintf: the general replacement
snprintf(buf, size, fmt, ...) writes at most size - 1 characters, always writes the terminating NUL when size is above zero, and returns the number of characters that would have been written if there had been room. The return value is what turns a silent cut into a check.
#include <stdio.h>
static int copy_name(char *dst, size_t dstsize, const char *src)
{
int n = snprintf(dst, dstsize, "%s", src);
if (n < 0)
return -1; /* encoding error */
if ((size_t)n >= dstsize)
return -2; /* truncated */
return 0;
}
int main(void)
{
char name[8];
int rc;
rc = copy_name(name, sizeof name, "Alex");
printf("rc=%d name=%s\n", rc, name);
rc = copy_name(name, sizeof name, "Alexandria");
printf("rc=%d name=%s\n", rc, name);
return 0;
}rc=0 name=Alex
rc=-2 name=AlexandThe second call needs 11 bytes and has 8, so snprintf stores Alexand plus the NUL, returns 10, and the check reports truncation. The caller decides what to do: reject the input, grow the buffer, or log and continue. The destination is always a valid string, which is more than strncpy promises.
Write "%s" as the format, never the data itself. snprintf(dst, size, src) hands attacker text to the format parser, which is a separate vulnerability covered in the format-string post of this series.
memcpy when you already know the length
If the length is already known, memcpy is the honest tool: it does what it says, and it does not scan for a NUL. The check goes in front of it.
#include <stdio.h>
#include <string.h>
static int copy_checked(char *dst, size_t dstsize, const char *src)
{
size_t len = strlen(src);
if (len >= dstsize)
return -1;
memcpy(dst, src, len + 1); /* includes the NUL */
return 0;
}
int main(void)
{
char small[4];
printf("%d\n", copy_checked(small, sizeof small, "abc"));
printf("%d\n", copy_checked(small, sizeof small, "abcd"));
return 0;
}0
-1"abc" is three characters and four bytes with the terminator, so it fits exactly. "abcd" needs five and is rejected. The test is len >= dstsize, not len > dstsize, because the terminator takes one byte, and that single character is the off-by-one that earlier posts in this series describe.
strlcpy and strlcat
BSD systems have long had strlcpy(dst, src, size) and strlcat. They always terminate, return the length they tried to create (the length of src for strlcpy), and are easy to check: strlcpy(dst, src, sizeof dst) >= sizeof dst means truncation. glibc added both in version 2.38, and POSIX.1-2024 standardized them. On older glibc, snprintf covers the same ground, and projects that need to build everywhere often carry a small portable copy.
One caveat: strlcpy measures the whole source length, so on an unterminated or enormous source it still scans every byte of it. For trusted, terminated strings that is fine.
Replacing strcat
strcat(dst, src) scans dst for its end on every call, and then appends with no limit. Loops of strcat are quadratic, and each call is another place to forget the check. Build the string with an offset instead:
#include <stdio.h>
int main(void)
{
const char *parts[] = { "usr", "local", "bin" };
char path[16];
size_t used = 0;
for (size_t i = 0; i < 3; i++) {
int n = snprintf(path + used, sizeof path - used,
"%s%s", i ? "/" : "", parts[i]);
if (n < 0 || (size_t)n >= sizeof path - used) {
fputs("path too long\n", stderr);
return 1;
}
used += (size_t)n;
}
printf("%s\n", path);
return 0;
}usr/local/binused tracks how many bytes are already in the buffer, sizeof path - used is the space left, and each call is checked against that remainder. The total is 13 characters plus the terminator, within the 16-byte buffer. If the parts grew past it, the program would print path too long instead of overwriting the stack. The loop never rescans the buffer, so the cost is linear.
Converting existing code
Search for the functions:
grep -nE '\b(strcpy|strcat|sprintf|vsprintf|gets)\b'.Find the destination's size. If it is an array in the same scope, use
sizeof. If it is a pointer, the size must be passed in, and adding that parameter is often the real change.Replace the call, then handle the truncation result. Silently truncating a file name or an authorization token is a bug of its own, so pick reject, grow or log deliberately.
Turn on warnings so new uses are caught. GCC and Clang warn on the unsafe patterns with
-Wall -Wextra, and-Wstringop-overflowand-Wformat-overflowreport cases where the sizes are provable.Compile with
-O2 -D_FORTIFY_SOURCE=3so any remaining call is checked at run time. Fortification is a net, not a license to keepstrcpy.
What not to do
strncpy and strncat look like the answer and are not. strncpy can leave the destination unterminated and pads short strings with zeros, which wastes time on large buffers. strncat takes the number of characters to append, not the buffer size, so the usual mistake is passing sizeof dst, which is too large. If you must use them, terminate explicitly and read the man page for the exact count semantics. Prefer the functions above.
Choosing between the replacements
The three tools answer different questions, and picking the right one keeps the code short. Use snprintf when you are formatting, or when you want one call that bounds the write and reports the length. Use memcpy after a check when you already hold the length, for example while parsing a field of a known size out of a packet, because it does exactly one thing and the compiler can optimize it well. Use strlcpy when the platform has it and the source is a trusted, terminated string.
Whatever you pick, decide the policy for the failure branch before writing the call. A command-line tool can print an error and exit. A server that receives a long header should reject the request with a client error and keep running. A function deep in a library should return an error code and leave the destination as a valid empty string, so a caller that ignores the code does not read garbage. Setting dst[0] = '\0' on the failure path costs one store and removes a whole class of follow-on bugs.
A note on performance
Programmers sometimes keep strcpy because it is faster. The bounded versions do a little more work, but the cost is a bounds comparison per call, and in most programs a string copy is nowhere near the hot path. If a profile shows a copy is hot, the right move is usually to avoid copying at all, by passing a pointer and a length or by keeping the original buffer alive, rather than removing the check.


