6 ms·
If your buffer isn't a NUL-terminated, then don't call a function that is only defined for NUL-terminated buffers. It's as simple as that. I'm baffled by how s
by dezgeg 7y ago
If your buffer isn't a NUL-terminated, then don't call a function that is only defined for NUL-terminated buffers. It's as simple as that.
I'm baffled by how some people claim strlcpy() is 'broken' or 'not safe' because it doesn't handle non-NUL-terminated inputs; the exact same thing applies to just about any function in the C standard library that takes strings as input. Are functions like strchr(), fopen(), printf(), strstr(), setenv() 'broken' as well?
- jandrese 7y agoYes, because cutting off the trailing NULL is a threat vector every C programmer needs to be conscious of whenever they're dealing with strings. But it's also a problem because maybe the programmer is using strlcpy to grab the first five lines of a 10TB memory mapped file. If you're not thinking about the implications of that return value it can be a real surprise.
- begriffs 7y ago> If your buffer isn't a NUL-terminated, then don't call a function that is only defined for NUL-terminated buffers. It's not that people want to pass strncpy source buffers that lack NUL termination, it's that strncpy in certain situations will not NUL terminate its results. https://begriffs.com/posts/2019-01-19-inside-c-standard-lib.html#string.h-strncpy https://begriffs.com/posts/2019-01-19-inside-c-standard-lib.... > some people claim strlcpy() is 'broken' Speaking of strlcpy, it thankfully doesn't have the problem that strncpy does. However strlcpy is not in the C standard or in POSIX, so can't be used portably. In C99 snprintf is a better choice.
- dezgeg 7y agoYes, strncpy() not NUL-terminating it's output is nasty and well-known. But the comment I was responding to was claiming strlcpy() being unsafe.
- deleted 7y ago[deleted]