r/cprogramming • • Aug 17 '26

C Strings: A 50-Year Mistake

https://longtran2904.substack.com/p/c-strings-a-50-year-mistake?r=8qz2zb&utm_campaign=post&utm_medium=web
212 Upvotes

172 comments sorted by

View all comments

Show parent comment

1

u/atarivcs Aug 17 '26

If you have a long string and you want to append more text to it, you have to search the whole string from the beginning to find the null terminator.

And then later if you want to append more text, you have to find the null terminator all over again.

2

u/NoNameSwitzerland Aug 17 '26

You anyway use a different structure when you do a lot of appending text, because you do not want to reallocate the array all the time. So then you anyway have to also store the size of the available space.

1

u/atarivcs Aug 17 '26

In which case you no longer have a plain c string, and the goalposts have moved.

I was just answering the parent question "how are c strings not efficient"

4

u/IdealBlueMan Aug 17 '26

Or you can store the length of the string whenever you change it.

2

u/atarivcs Aug 17 '26

Sure, but then you don't really have a plain c string anymore

2

u/WittyStick Aug 17 '26

It's actually more advantageous to couple the length to the char * on SYSV platforms, due to C's lack of multiple returns.

 String fn_returning_string(...);

If String is a fat pointer, then we can return both the pointer and length, without requiring another level of indirection (a pointer to a string structure), and without requiring awful to use "out parameters" to return both length and pointer - which are more expensive than just returning a fat pointer.

A fat pointer with the right ABI is not just "zero cost" - it's "less than zero" - it's more efficient than having a separate length and pointer variable.

2

u/IdealBlueMan Aug 17 '26

I’d say you still have the string, you also have information about that string.

1

u/orbiteapot Aug 17 '26

I mean... that is the point. Once you do that, you are no longer using classic C strings.

6

u/SakishimaHabu Aug 17 '26

That's the point though. They are basically atomic. You are free to do what you will with them, vs java, python, or js. Remember we're one step above assembly, but that's the intention.