[patch] abuse of strncpy

Peter Kjellerstedt peter.kjellerstedt at axis.com
Mon Jun 5 10:28:41 PDT 2006


> -----Original Message-----
> From: busybox-bounces at busybox.net 
> [mailto:busybox-bounces at busybox.net] On Behalf Of walter harms
> Sent: den 5 juni 2006 12:55
> Cc: busybox at busybox.net
> Subject: Re: [patch] abuse of strncpy
> 
> Just for my curiosity, "different semantics and functionality" ?
> 
> man strlcpy() says:
> 	 size_t strlcpy (char * dest, const char * src, size_t size);
> 
> while strncpy:
> 	char *strncpy(char *dest, const char *src, size_t n);

Well, there are two major differences between strncpy() and strlcpy():

1) strncpy() returns the dest address
   strlcpy() returns the resulting length which may be >= size, in which
   case the string was truncated
2) strncpy() pads the destination with NUL characters if there is space
   strlcpy() always adds one NUL character (if size > 0)

So, whether to use strncpy() or strlcpy() is not only about
copying a string and making sure it fits in a destination buffer.
A reason for using strncpy() may be due to security reasons where
you want to make sure that no random data is left in the destination
buffer after the copied string. On the other hand, if that is of
no concern, strlcpy() should be the right choice as it needs to
copy/pad less data and thus should be faster if the destination
buffer is large.

For more information about strncpy() vs strlcpy(), see:
http://www.courtesan.com/todd/papers/strlcpy.html

> A grep over busybox (some older version) shows that the 
> return value is actualy used only once.
> 
> The bb_strlcpy() is only used for system that do not provide 
> a strlcpy by them self (perhaps this can be dropped).
> 
> re,
>   wh

//Peter


More information about the busybox mailing list