DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 

strlcpy(S-osr5)


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-osr5) and strncat(S-osr5). 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-osr5), string(S-osr5), strncat(S-osr5), 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;


© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005