[PATCH v3] Implement strlcpy [BZ #178]

Paul Eggert eggert@cs.ucla.edu
Sat Oct 31 10:37:00 GMT 2015


Rich Felker wrote:

> There is a general principle,
> which needs to be promoted rather than undermined, that a function
> cannot have side effects/alter the value of objects outside of its
> documented behavior.

Regardless of whether that is an (undocumented?) general principle, this is a 
user manual not a formal standard.  In this particular context it's helpful to 
describe strlcpy's behavior carefully, since it's explained right after 
strncpy's and the reader might otherwise easily get confused into the 
misimpression that strlcpy behaves like strncpy except for guaranteeing 
null-termination when DESTLEN is nonzero.

> Requiring the
> argument to point to "a string" also expresses the null termination
> requirement. This is the same language used in the C standard for
> string functions.

Again, the point of the documentation is to be clear and useful, and it's 
helpful to spell things out given the strncpy context.  (Besides, this is a 
manual that contains phrases like "it is more efficient and works even if the 
string @var{s} is not null-terminated", so it's a bit much to expect the reader 
to know that "string" always means "null-terminated". :-)

> __-prefixed functions should never
> be a public API intended for applications to use.

Yes, that's fine.  My point was about the non-'__'-prefixed name, where it 
appears we agree.

> No, the fortify version should just abort when this contract is
> broken.

The idea was that this contract should be memmove-based, not memcpy-based, which 
means the fortify version would not abort if the arguments overlap. Still, I see 
your point: if we wanted move semantics, we'd have called the function 
'strlmove' or something like that. So I withdraw the suggestion to change the 
contract, and instead suggest that we add overlapping strings to our list of 
when not to use strlcpy, e.g,:

Often @code{strlcpy} is not what you want, because it does not null-terminate 
the destination if the destination's size is zero, it can leave junk data behind 
in the destination, it can do useless work when the source is long and the 
destination short, it requires the source to be null-terminated even when it is 
longer than the destination, it can crash if the source and destination overlap, 
and it may truncate the destination.  Although one alternative is 
@code{strncpy}, it is usually better to use dynamic memory allocation and 
functions such as @code{strdup} or @code{asprintf} to construct strings.


All in all, I'd still rather not add this poorly-designed API to the library.



More information about the Libc-alpha mailing list