3 ms·
I don’t understand why silently truncating strings is considered to be acceptable practice. If you have the length of both, simply assert the length of the des
by hedora 8y ago
I don’t understand why silently truncating strings is considered to be acceptable practice.
If you have the length of both, simply assert the length of the destination is <= the length of the source. Problem solved (bugs become obvious in testing).
- brucedawson 8y agoWhat about user input, strings coming from files, and in general the diversity of things that can go wrong when your product ships. This is particularly important if your product is attacked by those who would like to exploit it. Asserts are necessary, but not sufficient.
- russdill 8y agoBecause the API is stupid and not intuitive. It's for memory buffers where the string is either NULL terminated or it is the length of the memory buffer. This saves an extra byte. yay?
- russdill 8y agoI'll add that it's really handy for that specific situation as it also avoids leaking uninitialized bytes.
- gweinberg 8y agoThe more I think about this, the more sense it makes to say you should check the length of the buffer before they copy. I'm not sure an assert is always right, exactly what should be done if the string doesn't fit may depend on what the program is doing. But silently truncating is generally not the right thing to do.
- brucedawson 8y agostrcpy_s does this. It has a template variant to infer the length of the destination buffer and it will terminate the program if the source string is too large. If the destination buffer doesn't have a fixed length then it will fail to compile. This is similar to your suggestion with these improvements: - Template deduction of the destination size is done - this is essential to avoid bugs - Detection of overwrites is done in release builds as well as during testing - Detection of overwrites is automatic - it doesn't require manually adding asserts to call sites - strcpy_s exists in some standard libraries