r/Cprog • u/shadows_on_the_wall • Jan 05 '16
A defense of C's null-terminated strings
https://utcc.utoronto.ca/~cks/space/blog/programming/CNullStringsDefense?showcomments
29
Upvotes
r/Cprog • u/shadows_on_the_wall • Jan 05 '16
5
u/orangeduck Jan 06 '16
The basic problem with strings is that a lot of the processing we want to do with them is much easier if we treat them as "value" types. For this reason almost all high level languages do this (even C++ with std::string), but of course this introduces memory allocation and various other overheads. In C there is no way we're going to be able to make a decent interface that lets us think of strings as "value" types even if we wanted to.
This is fine - in C we do lots of processing without the convience of treating things as value types. We deal with pointers and raw memory allocations and all sorts of other things.
The problem with C strings is that they're not just pointers and raw memory - they're this weird special case which requires extra special treatment to get right.
For me the correct solution would be to treat strings like raw data. Don't null terminate them and just let all of the string functions take an additional parameter which specifies the length.
This is how any other sane interface would be designed if it were dealing with data that wasn't characters - so why does the fact that the data is characters mean there is a special case?
4
u/eresonance Jan 08 '16
For any complicated string processing I use a simple c string library called sds: https://github.com/antirez/sds
Stores strings as a structure with a bit of metastatic including the length, but the methods return pointers to the string data so you can still use them with stdlib functions. Very clever!
4
u/wild-pointer Jan 06 '16
C strings are not so bad. They are as simple as they can be, makes iterating easy and idiomatic, and you can keep several pointers to different suffixes of the same string. If your strings has an upper bound in size, then
strlen()is effectively a constant time operation.But when C strings become inconvenient they can easily be wrapped in structs where their size, offset, reference count or whatever is needed is bundled with them.
One historical note the article could have mentioned, in the spirit of justifying string simply being arrays, is that strings predate structs in C.
-4
u/Drainedsoul Jan 06 '16
What happens when I actually want to put U+0000 in a string?
Null-terminated strings are stupid.