strlcpy()
[Posted May 27, 2003 by corbet]
Years of buffer overflow problems have made it clear that the classic C
string functions -
strcpy() and friends - are unsafe. Functions
like
strncpy(), which take a length argument, have been presented
as the safe alternatives. But
strncpy() has always been poorly
suited to the task; it wastes time by zero-filling the destination string,
and, if the string to be copied must be truncated, the result is no longer
NULL-terminated. A non-terminated string can lead to overflows
and bugs in its own right. So Linus
finally got
fed up and put together a new
copy_string() function which
does what most
strncpy() users really wanted in the first place.
As is often the case with this sort of security-related improvement, OpenBSD got there
first. In fact, back in 1996, the OpenBSD team came up with a new
string API which avoids the problems of both strcpy() and
strncpy(). The resulting functions, with names like
strlcpy(), have been spreading beyond OpenBSD. The basic function
is simple:
size_t strlcpy(char *dest, const char *src, size_t size);
The source string is copied to the destination and properly terminated; the
return value is the length of the source. If that length is greater than
the destination string, the caller knows that the string has been
truncated.
Linus agreed that following OpenBSD's lead was the right way forward, and
strlcpy() is in his BitKeeper repository, waiting for 2.5.71.
There has also been a flurry of activity to convert kernel code over to the
new function. By the time 2.6.0 comes out, strncpy() may no
longer have a place in the Linux kernel.
(
Log in to post comments)