Ushering out strlcpy()
Ushering out strlcpy()
Posted Sep 2, 2022 11:16 UTC (Fri) by mtodorov (guest, #158788)Parent article: Ushering out strlcpy()
Just occurred to me, maybe it is a stupid idea ...
What if strlcpy() was fixed instead of changing 1,000s of occurrences?
Changing the strlen(src) to strnlen(src, size) should suffice. This would both prevent segfaults for long unterminated strings and preserve function semantics.
The fix is simple:
size_t strlcpy(char *dest, const char *src, size_t size)
{
size_t ret = strnlen(src, size);
if (size) {
size_t len = (ret >= size) ? size - 1 : ret;
memcpy(dest, src, len);
dest[len] = '\0';
}
return ret;
}
Am I making any sense to you? strnlen (src, size) is said to be POSIX-2008 compliant ...
