RE: [RFC] strcpys(): New function for copying strings safely

From: David Laight
Date: Mon Jun 28 2021 - 04:15:44 EST


From: Alejandro Colomar
> Sent: 27 June 2021 20:47
>
> On 6/27/21 9:26 PM, Alejandro Colomar (man-pages) wrote:
> >
> > It is designed so that usage requires the minimum number of lines of
> > code for complete usage (including error handling checks):
> >
> > [[
> > // When we already checked that 'size' is >= 1
> > // and truncation is not an issue:
> >
> > strcpys_np(size, dest, src, NULL);
>
> Also, given how unlikely this case is, I have in my code:
> `[[gnu::warn_unused_result]]`

warn_unused_result is such a PITA it should never have been invented.
At least no one seems to have been stupid enough to apply it to fprintf()
(you need to do fflush() before looking for errors).

In most cases strcpy() is safe - but if the inputs are 'corrupt'
horrid things happen - so you need truncation for safety.
But you really may not care whether the data got truncated.

The other use is where you want a sequence of:
len *= str_copy(dest + len, dest_len - len, src);
But don't really want to test for overflow after each call.

In this case returning the buffer length (including the added
'\0' on truncation works quite nicely.
No chance of writing outside the buffer, safe truncation and
a simple 'len == dest_len' check for overflow.

OTOH there are already too many string copy functions.

David

-
Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK
Registration No: 1397386 (Wales)