DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH
 

strlcpy(S)


strlcpy, strlcat -- size-bounded string copying and concatenation

Syntax

cc ... -lc
   #include  <string.h>
   

size_t strlcpy(char *dst, const char *src, size_t size)

size_t strlcat(char *dst, const char *src, size_t size)

Description

The strlcpy( ) and strlcat( ) functions copy and concatenante strings, respectively. They are designed to be safer, more consistent, and less error prone replacements for strncpy(S) and strncat(S). Unlike those functions, strlcpy( ) and strlcat( ) take the full size of the buffer, not just the length, and guarantee to NUL terminate the result as long as size is greater than 0. Note that you should include a byte for the NUL in the size value.

The strlcpy( ) function copies up to size-1 characters from the NUL terminated string, src, to dst, NUL terminating the result.

The strlcat( ) function appends the NULL terminated string src to the end of dst. It will append at most size-strlen(dst)-1 bytes, NUL terminating the result.

Return values

The strlcpy( ) and strlcat( ) functions return the total length of the string they tried to create. For strlcpy( ), this is the length of src. For strlcat( ), this is the initial length of dst plus the length of src. While this may seem somewhat confusing, it was done to make truncation detection simple.

Standards conformance

These functions are not part of any currently defined standard but are based on functions included in OpenBSD. The idea and an early implementation used material Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>. All rights reserved.

See also

snprintf(S), string(S), strncat(S), strncpy( )

See Todd C. Miller, Consistant Safe strcpy and catenation, Freenix track:1999 USENIX Annual Technical Conference. Also ftp::/ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcat.c.

Examples

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, use code like the following:
   char	*dir, *file, pname[MAXPATHNAMELEN];
   

...

if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname)) goto toolong; if (strlcat(pname, file, sizeof(pname)) >= sizeof(pname)) goto toolong;

Because we know how many characters were copied the first time, using a copy instead of an append speeds execution a bit, although code like this largely defeats the purpose of strlcpy( ) and strlcat( ):
   char	*dir, *file, pname[MAXPATHNAMELEN];
   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;


© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003