Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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)


Truncating 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


You will be surprised to learn that there were programmers who did not make the buffers large enough.


No matter how big you make it. Someone will find a way to overflow it.


Someone 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).


Except to properly implement that you'll need to deal with grapheme clusters.


I 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?".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: