4 ms·
I've never understood the circumstances where it is ok for a copy/concatenate operation to also include a bonus "truncate the result" operation at the end. I'm
by TheNewAndy 3y ago
I've never understood the circumstances where it is ok for a copy/concatenate operation to also include a bonus "truncate the result" operation at the end. I'm a believer that you should use strcpy and strcat, and also make sure your buffers are large enough. If you can't make them large enough, then you can't do the operation you are trying to do (and I would say that doing it incorrectly via truncation isn't obviously better since this seems like silent corruption to me)
- dwattttt 3y agoSomeone will likely be able to answer more specifically, but I seem to recall an old common operation was filling fixed width text fields; truncating a message would make sense there (not ideal, but probably familiar).
- gdprrrr 3y agoExcept to properly implement that you'll need to deal with grapheme clusters.
- tialaramex 3y agoI expect the parent is thinking of why strncpy is the way it is, and the people who built that were glad if their terminal had both uppercase and lowercase letters, they didn't have Unicode, or grapheme clusters, their concern wasn't "will this string fit in this many pixels on my 24" flat panel?" but "Will this string fit in these 10 bytes where the filename needs to go in the directory data structure of the filesystem?".
- tedunangst 3y agoYou will be surprised to learn that there were programmers who did not make the buffers large enough.
- ben_bai 3y agoNo matter how big you make it. Someone will find a way to overflow it.
- theamk 3y agoTruncating strings is a practical alternative that provides useful signal with minimal extra error handling code. Yes, in the ideal world there will be no string truncation, but if there are no alternatives in a lot of cases truncation is better than nothing. Which of those two error messages would you rather see? sprintf: output buffer is to small or fopen: cannot open file /usr/bin/superlong-dist-path/208277409874874/fi