On 10/11/2023 05:36, Paul Eggert wrote: > On 2023-11-09 15:48, Alejandro Colomar wrote: >> I'd then just use strlen(3)+strcpy(3), avoiding >> strncpy(3). > > But that is vulnerable to the same denial-of-service attack that strlcpy is vulnerable to. You'd need strnlen+strcpy instead. > > The strncpy approach I suggested is simpler, and (though this doesn't matter much in practice) is typically significantly faster than strnlen+strcpy in the typical case where the destination is a small fixed-size buffer. > > Although strncpy is not a good design, it's often simpler or faster or safer than later "improvements". As you say, it is a known API. I recall looking for a standardized bounded string copy a few years ago that avoids pitfalls: 1) cost of any initial strnlen() reading memory to determine input src size 2) accepts a src_max_size to actually try to copy from src 3) does not truncate by writing anything to the buffer if there isn't enough space in the dest_max_size to fit src_max_size 4) check for NULL pointers 5) probably other thing I've overlooked Something like this API: int my_str_copy(char *dest, const char *src, size_t dest_max_size, size_t src_max_size, size_t * dest_written); These sizes are including any NUL terminating byte. 0 on success, or an an error code like EINVAL, or ERANGE if would truncate All comments welcome. Kind regards, Jonny