Strlcpy and strlcat
strlcat() functions first appeared in OpenBSD 2.4, and FreeBSD 3.3,
According to their man page, they’re doing
strlcat()take the full size of the destination buffer and guarantee
NUL-termination if there is room. Note that room for the
NULshould be included in
strlcpy()copies up to
dstsize - 1characters from the string
NUL-terminating the result if
srcto the end of
dst. It will append at most `dstsize
- strlen(dst) - 1
characters. It will thenNUL
or the originaldst
string was longer thandstsize
(in practice this should not happen as it means that eitherdstsize
is incorrect or thatdst` is not a proper string).
If the return value is
>= dstsize, the output string has been truncated. It is the caller’s responsibility to handle this.
Meaning that if a developer miscalculates the size of the destination buffer and makes it too short, the string will be silently truncated. This might prevent some buffer-overflow, but you’ll get corrupted data in exchange.
Moreover, it’s a nice way to introduce infoleaks:
strcpy will copy
dst, and pad the remaining buffer with
strlcpy won’t, leaving
unallocated memory in the buffer. This has been a
constant source of infoleaks on Linux.
strlcpy is also doing an
on the source, leading to a crash if not NULL-terminated. And even
if it is, it’s still doing the
strlen on the whole source, even if only a
couple of chars are to be copied.
A quick glance
at OpenBSD’s source code shows that the return value of
As of 2015, at least OpenBSD, FreeBSD, NetBSD, Solaris, Mac OS X, and QNX provide these functions. Implementations are also present in popular Open Source projects like SDL, GLib, ffmpeg and rsync. The Linux kernel also uses them internally.