|STPCPY(3)||Library Functions Manual||STPCPY(3)|
*dst, const char
*dst, const char
stpncpy() functions copy the string src to dst (including the terminating ‘
stpncpy() function copies not more
than len characters into dst,
\0’ characters if
src is less than len characters
long, and not terminating dst if the
length of src is greater than or equal to
If the src and dst strings overlap, the behavior is undefined.
stpcpy() function returns a pointer to the terminating ‘
\0’ character written into dst.
stpncpy() function returns a pointer
to the first ‘
\0’ character written
into dst, or to &dst[len] if
the length of src is greater than or equal to
stpcpy() is to build up a string from multiple elements. The following example builds up a pathname from directory and file components using
char *dir, *file, pname[PATH_MAX]; ... if (strlen(dir) + strlen("/") + strlen(file) >= sizeof(pname)) goto toolong; stpcpy(stpcpy(stpcpy(pname, dir), "/"), file);
However, the size check required to avoid a buffer overflow is error prone since the check can become out of sync with the code that performs the copy.
One might expect that
stpncpy() could be
safely used instead, but it suffers from the same defects as
strncpy(). The example below using
stpncpy() is even more prone to error and will not
detect when truncation occurs:
char *dir, *file, pname[PATH_MAX]; char *p1, *p2; ... p1 = stpncpy(pname, dir, sizeof(pname) - 1); p2 = stpncpy(p1, "/", sizeof(pname) - 1 - (p1 - pname)); stpncpy(p2, file, sizeof(pname) - 1 - (p2 - pname)); pname[sizeof(pname) - 1] = '\0';
A safer (and simpler) approach is to use
char *dir, *file, pname[PATH_MAX]; int len; ... len = snprintf(pname, sizeof(pname), "%s/%s", dir, file); if (len >= sizeof(pname)) goto toolong;
In most cases, it is better to use
stpncpy() functions conform to IEEE Std 1003.1-2008 (“POSIX.1”).
stpcpy() first appeared in the Lattice C AmigaDOS compiler (1986 or earlier). The function
stpncpy() first appeared in the GNU C library version 1.07 (1993). Both functions have been available since OpenBSD 5.1.
|February 23, 2014||OpenBSD-current|