Hacker News new | past | comments | ask | show | jobs | submit login

Did you read the link? The point was that in idiomatic C, you pass a string to a function by passing a raw pointer to a char-array buffer together with an external length.



Yes I read the link. It makes the unfounded claim that heap allocated strings were never intended to use the NUL character as the means of determining length. Get a 1st edition of K&R and see what fraction of functions in the standard library pass a length with a string.

Get an SVR4 API manual and do the same. After doing this I don't find this argument to be compelling.


In the end, it's about efficiency and redundancy. If a function is going to have to do something with every character of a string (e.g. copy it into a new buffer), and you don't have very many registers reserved in your calling convention (especially true for e.g. system calls), then it's silly to pass an explicit length if you know you've already NUL-terminated the string in its buffer.

All Unix system-call wrapper functions were specified this way, because it is guaranteed that they will need to move the string data from a user-space data structure to a kernel-space data structure (copying it wholesale in the process) before manipulating it. The NUL-terminated string can, in this case, be thought of as an encoded wire format for passing a string between the userland process and the kernel.

And because the Unix system-call wrappers--the most visible and useful parts of the C stdlib--followed this convention, C programmers generalized it into a convention for passing strings in general, even between functions in the same memory-space that can afford whatever registers they like.

If you're not going to iterate over everything in the passed buffer, though, C intended you to do things more like sprintf: take a destination buffer, and explicit size; write to the destination buffer, without scanning for a NUL first as a place to begin, and without appending a NUL afterward; and return an explicit size in bytes written.




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

Search: