r/cprogramming • u/Elifire12 • Sep 07 '26
I Made a String Library to Fix C Strings
I wrote an article about this as well. Here it is.
There I explain why I do not like NUL-terminated strings and how I implemented my own simple string library in C.
If you have some spare time I would really appreciate some feedback on the article and the library.
The code is sitting on a codeberg repository.
Also, tell me what you think about C-style strings. Do you like them? Do you use them, or do you also tend to roll your own pointer + length structs?
0
Upvotes
5
u/wallstop-dev Sep 07 '26 edited Sep 08 '26
You forget the links.
Interested to hear how it compares to Walter Bright's solution: https://www.digitalmars.com/articles/C-biggest-mistake.html
Edit: Woops, I meant this link: https://news.ycombinator.com/item?id=42439654
1
u/beragis Sep 07 '26
Why the heck would you do that? Putting the String pointer and length in a separate structures is an extra indirection.
First off such a structure is not needed in C. The only time you would need to change the format is if you are accessing the string through another obscure compiled language. Most non-C programs that don’t follow the C style for string types, place the length first followed by the string.
Modern CPUs don’t really care, but some older CPUs and underlying operating system calls are optimized for C-style.
2
u/jason-reddit-public Sep 08 '26
C style strings are fine if you treat them as immutable utf-8 that can't express NUL bytes.
If you want random access and such, then a utf-32 (growable) array should be good for 25 years or more. Of course this makes ascii strings much bigger but besides that, chars are fixed size so lots of advantages for inserting into and such.
If you just want to collect strings, you have choices. An array of utf-8 strings handles text with no NUL bytes, otherwise you may want another abstraction (say a growable byte array containing 1 to N byte utf-8 encoded code points ... much denser than utf-32 above but trickier to work with for many things).
This is all a bit java like - except 16 -> 32 to avoid edge cases they have to deal with which defeats the purpose of wide characters (though by no means "solves" text handling...)
This is C so everyone can choose what's right for them. ;)
1
u/grimvian Sep 08 '26
I actually like C strings exactly as they are. If my C strings don't work as intended i know I have messed some of my code up.
0
u/[deleted] Sep 08 '26
[deleted] — view deleted comment