Re: strncpy clarify result may not be null terminated

Alejandro Colomar
2023-11-09T12:43:27Z

[-- Attachment #1: Type: text/plain, Size: 1158 bytes --]

On Thu, Nov 09, 2023 at 12:38:37PM +0100, Alejandro Colomar wrote:
> If you would want to write something based on Michael Kerrisk's article,
> you could do this:
>
> ssize_t
> strxcpy(char *restrict dst, char *restrict src, size_t dsize)
> {
> if (strlen(src) < dsize)

Heh, here's my off-by-one bug of the day. Good thing is I can fix it in
a single place; unlike calling strncpy(3) all the time.

This should have been <=.

Cheers,
Alex

> return -1;
>
> strcpy(dst, src);
> }
>
> You may also want to calculate 'dsize' automagically, to avoid human
> error, in case it's an array, so you could write a macro on top of it:
>
> #define STRXCPY(dst, src) strxcpy(dst, src, ARRAY_SIZE(dst))
>
> These are just small wrappers over standard functions, so you shouldn't
> have problems adding them to your project.
>
> This is my long term plan for shadow-utils, indeed. I'm first
> transforming strncpy(3) calls into strlcpy(3) to remove the superfluous
> padding, and later will use this strxcpy() to remove the truncated
> strings to avoid misinterpretation.

--
<https://www.alejandro-colomar.es/>