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)) {
        len--;
        handle_trunc();
}


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

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

- memccpy(3)
        ISO C
        good performance
        bad interface

- stpecpy()
        custom
        good performance
        good interface


What are your thoughts?

Regards,

Alex


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

_______________________________________________
Pkg-shadow-devel mailing list
[email protected]
https://alioth-lists.debian.net/cgi-bin/mailman/listinfo/pkg-shadow-devel

Reply via email to