Manpages - strlcpy.3bsd
(See
for include usage.)
The
and
functions copy and concatenate strings respectively. They are designed to be safer, more consistent, and less error prone replacements for
and
Unlike those functions,
and
take the full size of the buffer (not just the length) and guarantee to NUL-terminate the result (as long as
is larger than 0 or, in the case of
as long as there is at least one byte free in
Note that a byte for the NUL should be included in
Also note that
and
only operate on true
strings. This means that for
must be NUL-terminated and for
both
and
must be NUL-terminated.
The
function copies up to
- 1 characters from the NUL-terminated string
to
NUL-terminating the result.
The
function appends the NUL-terminated string
to the end of
It will append at most
- strlen(dst) - 1 bytes, NUL-terminating the result.
The
and
functions return the total length of the string they tried to create. For
that means the length of
For
that means the initial length of
plus the length of
While this may seem somewhat confusing, it was done to make truncation detection simple.
Note, however, that if
traverses
characters without finding a NUL, the length of the string is considered to be
and the destination string will not be NUL-terminated (since there was no space for the NUL). This keeps
from running off the end of a string. In practice this should not happen (as it means that either
is incorrect or that
is not a proper
string). The check exists to prevent potential security problems in incorrect code.
The 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
and
As a matter of fact, the first version of this manual page got it wrong.
The
and
functions first appeared in
and made their appearance in