|
NAMEstrlcpy , strlcat —
size-bounded string copying and concatenation
LIBRARYStandard C Library (libc, -lc)SYNOPSIS#include <string.h>
size_t
size_t
DESCRIPTIONThestrlcpy () and strlcat ()
functions copy and concatenate strings with the same input parameters and
output result as
snprintf(3).
They are designed to be safer, more consistent, and less error prone
replacements for the easily misused functions
strncpy(3)
and
strncat(3).
If the src and dst strings overlap, the behavior is undefined. RETURN VALUESBesides quibbles over the return type (size_t versus int) and signal handler safety (snprintf(3) is not entirely safe on some systems), the following two are equivalent:n = strlcpy(dst, src, len); n = snprintf(dst, len, "%s", src); Like
snprintf(3),
the If the return value is EXAMPLESThe following code fragment illustrates the simple case:char *s, *p, buf[BUFSIZ]; ... (void)strlcpy(buf, s, sizeof(buf)); (void)strlcat(buf, p, sizeof(buf)); To detect truncation, perhaps while building a pathname, something like the following might be used: char *dir, *file, pname[MAXPATHLEN]; ... if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname)) goto toolong; if (strlcat(pname, file, sizeof(pname)) >= sizeof(pname)) goto toolong; Since it is known how many characters were copied the first time, things can be sped up a bit by using a copy instead of an append: char *dir, *file, pname[MAXPATHLEN]; size_t n; ... n = strlcpy(pname, dir, sizeof(pname)); if (n >= sizeof(pname)) goto toolong; if (strlcpy(pname + n, file, sizeof(pname) - n) >= sizeof(pname) - n) goto toolong; However, one may question the validity of such optimizations, as
they defeat the whole purpose of SEE ALSOsnprintf(3), strncat(3), strncpy(3), wcslcpy(3)Todd C. Miller and Theo de Raadt, strlcpy and strlcat -- Consistent, Safe, String Copy and Concatenation, Proceedings of the FREENIX Track: 1999 USENIX Annual Technical Conference, USENIX Association, http://www.usenix.org/publications/library/proceedings/usenix99/, full_papers/millert/millert.pdf, June 6-11, 1999. HISTORYThestrlcpy () and strlcat ()
functions first appeared in OpenBSD 2.4, and
FreeBSD 3.3.
Visit the GSP FreeBSD Man Page Interface. |