[Pkg-shadow-devel] Replace strncpy(3) by stpecpy()

Alejandro Colomar (man-pages) alx.manpages at gmail.com
Tue Feb 15 23:01:06 GMT 2022

Hi Serge,

I proposed a few months ago to replace strncpy(3) by strlcpy(3BSD)[1]. 
However, strlcpy(3BSD) is not in glibc, and anyway, it's not ideal: 
strlcat(3BSD) has quadratic time complexity, since it needs to re-read 
the whole string for each copy.

[1]: <https://github.com/shadow-maint/shadow/issues/468>

I designed a function (based on other earlier interfaces, including 
strecopy() and strlcpy(3BSD); see 
<https://software.codidact.com/posts/285946>) that provides a better 
behavior than any other string copy functions, with linear time complexity.

I propose to use it here, implementing it inside shadow-utils.

It is defined as:

char *stpecpy(char *dst, char *restrict src, char *end)
	char *p;

	p = memccpy(dst, src, '\0', end + 1 - dst);
	if (p != NULL)
		return p - 1;
	/* truncation detected */
	*end = '\0';
	return end + 1;

To be used as:

end = buf + sizeof(buf) - 1;
len = stpecpy(stpecpy(buf, "Hello", end), " world", end) - buf;
if (len == sizeof(buf)) {

So the 3 main alternatives to strncpy(3) are:

- strlcpy(3BSD) + strlcat(3BSD)
	good interface
	bad performance

- memccpy(3)
	good performance
	bad interface

- stpecpy()
	good performance
	good interface

What are your thoughts?



Alejandro Colomar
Linux man-pages comaintainer; http://www.kernel.org/doc/man-pages/

More information about the Pkg-shadow-devel mailing list