Non-standard C function originating in OpenBSD: `strlcpy` copies null-terminated string to non-overlapping buffer of size `n`. Returns source length `s` (excluding terminating \0). Unless `n` == 0, the destination string is always null-terminated. If `s` + 1 > `n`, the destination copy is truncated. Use this tag for questions about the function's usage, implementation and relation to other string functions, such as `strcpy` or `strncpy`.
strlcpy
is a popular strcpy
replacement originating in OpenBSD, where it is available in the <string.h>
standard header. On other systems, it is available through libbsd
. Many projects have their custom implementation of strlcpy
, including the Linux kernel.
Unlike strncpy
, it always terminates the string, and if the buffer is longer than needed, it does not waste time overwriting the excess space with zeros.
Wikipedia says:
The most popular [according to GitHub search] replacement [of
strcpy
andstrcat
] are thestrlcat
andstrlcpy
functions, which appeared in OpenBSD 2.4 in December, 1998. These functions always write one NUL to the destination buffer, truncating the result if necessary, and return the size of buffer that would be needed, which allows detection of the truncation and provides a size for creating a new buffer that will not truncate. They have been criticized on the basis of allegedly being inefficient and encouraging the use of C strings (instead of some superior alternative form of string). Consequently, they have not been included in the GNU C library (used by software on Linux), although they are implemented in the C libraries for OpenBSD, FreeBSD, NetBSD, Solaris, OS X, and QNX, as well as in alternative C libraries for Linux, such as musl. The lack of GNU C library support has not stopped various software authors from using it and bundling a replacement, among other SDL, GLib, ffmpeg, rsync, and even internally in the Linux kernel. Open source implementations for these functions are available.
Related tags
Sources
strlcpy(3)
OpenBSD manpage- OpenBSD's implementation of
strlcpy
andstring.h
src/strlcpy.c
in libbsdlib/string.c
in Linux- Wikipedia article C string handling, § Replacements
- Wikibooks book C Programming, § C Reference/nonstandard/strlcpy