5 ms·
> Dammit, it is not safe. It hides bugs in programs. If a string is too long for an allocated memory block the copying must not simply silently stop. This is s
by huhtenberg 8y ago
> Dammit, it is not safe. It hides bugs in programs. If a string is too long for an allocated memory block the copying must not simply silently stop.
This is spot on. There are very few cases when silently truncating a copy of a string is an OK thing to do.
- wyldfire 8y agoI think it's not genuine to describe the behavior of strlcpy() as "silently truncating". strlcpy() is documented as "If the return value is >= dstsize, the output string has been truncated. It is the caller's responsibility to handle this."
- thefifthsetpin 8y agoSilent doesn't imply undocumented. strlcpy's truncation is silent because it doesn't inform the caller about whether or not it truncated.
- stephencanon 8y agoThe caller is informed: "If the return value is >= dstsize, the output string has been truncated"
- akkartik 8y agoHow is returning a different value "silent"? It's informing the caller just fine. This is C we're talking about. Always be checking return values. (And errno! And errno! And errno!)
- bripeace 8y agoCareful! Errno can be set even when there is not an error.it's value is only relevant when the return value of the function indicates an error. That said there are some functions where the possible return values can't indicate an error. In those cases errno should be set to zero before the function call and then a change during will alert you to an error. Why it's like this I have no idea but it's pretty annoying.
- nothrabannosir 8y ago> Why it's like this I have no idea but it's pretty annoying. The bit about errno possibly being non-zero but not indicating error unless the function does? I guess because the called function can itself call functions / libs which set errno and properly handle those (or just not care). Without the "errno only has meaning if the function returns error" guard, every single function needs to always reset errno to zero before returning, which is annoying and will almost certainly not happen in the majority of cases. When the function has no way to communicate error, there is no other option but to use errno. But it's good that it's the exception, I imagine.
- Sohcahtoa82 8y agoBut....it does inform the caller via the return value...what are you expecting it to do?
- raverbashing 8y agoI'll take truncating errors in place of non-null terminating errors, thanks. Can it makes things worse? Yes. But C is broken.
- loeg 8y agoOk, but, we've already got that kind of foot-shooting enabled by strncpy(), and glibc can't remove it as it is part of ISO C. If glibc must contain a truncating string copy, I'd much rather have strlcpy than strncpy. Do you find that persuasive?