OpenBSD manual page server

Manual Page Search Parameters

STRNCAT(3) Library Functions Manual STRNCAT(3)

strncatconcatenate a string with part of another

#include <string.h>

char *
strncat(char *dst, const char *append, size_t count);

The () function appends not more than count characters of the string append to the end of the string found in the buffer dst. Space for the terminating ‘\0’ should not be included in count.

Bounds checking must be performed manually with great care. If the buffer dst is not large enough to hold the result, subsequent memory will be damaged.

The strncat() function returns the pointer dst.

The following example shows how to use strncat() in conjunction with strncpy(3):

char buf[BUFSIZ];
char *base, *suffix;

(void)strncpy(buf, base, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
(void)strncat(buf, suffix, sizeof(buf) - 1 - strlen(buf));

The above will copy as many characters from base to buf as will fit. It then appends as many characters from suffix as will fit. If either base or suffix are too large, truncation will occur without detection.

The above example shows dangerous coding patterns, including an inability to detect truncation. strncat() and strncpy() are dangerously easy to misuse. The strlcpy(3) and strlcat(3) functions are safer for this kind of operation:

if (strlcpy(buf, base, sizeof(buf)) >= sizeof(buf) ||
    strlcat(buf, suffix, sizeof(buf)) >= sizeof(buf))
        goto toolong;

or for greatest portability,
if (snprintf(buf, sizeof(buf), "%s%s",
    base, suffix) >= sizeof(buf))
        goto toolong;

strlcpy(3), wcscat(3), wcslcpy(3)

The strncat() function conforms to ANSI X3.159-1989 (“ANSI C89”).

The strncat() function first appeared in Version 7 AT&T UNIX.

April 19, 2014 OpenBSD-5.6