STPCPY(3) | Library Functions Manual | STPCPY(3)

# NAME

`stpcpy`, `stpncpy` — copy strings

# SYNOPSIS

`#include <string.h>`

char *
`stpcpy`(char *dst, const char *src);

char *
`stpncpy`(char *dst, const char *src, size_t len);

# DESCRIPTION

The `stpcpy`() and `stpncpy`() functions copy the string src to dst (including the terminating ‘`\0`’ character).

The `stpncpy`() function copies not more than len characters into dst, appending ‘`\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 len.

If the src and dst strings overlap, the behavior is undefined.

# RETURN VALUES

The `stpcpy`() function returns a pointer to the terminating ‘`\0`’ character written into dst.

The `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 len.

# EXAMPLES

The most common use of `stpcpy`() is to build up a string from multiple elements. The following example builds up a pathname from directory and file components using `stpcpy`():

    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 `snprintf`():

    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 `snprintf`(), `strlcpy`(), or `strlcat`().

# SEE ALSO

snprintf(3), strcpy(3), strlcpy(3), strncpy(3)

# STANDARDS

The `stpcpy`() and `stpncpy`() functions conform to IEEE Std 1003.1-2008 (“POSIX.1”).

# HISTORY

The function `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 | Debian