r/cprogramming • u/die-Banane • May 05 '26
How to do strings properly?
I just started learning C and I often read on the internet that it is bad practice to use null terminated strings, so my question is what should I do instead?
29
Upvotes
View all comments
1
u/DawnOnTheEdge May 06 '26 edited May 06 '26
I suggest you create a string-slice type, something like
This helps prevent buffer overruns by making sure the program always remembers the string length. It can avoid extra calls to
strlen(). It can represent substrings without modifying the string. Functions can return slices and be chained together much more easily than if string pointers and lengths were stored in separate variables.If you can design your API around it, you can pass in and return these objects. Otherwise, you will write a sort of constructor like
You will often know a maximum size and use
strnlen(). Since this is C, you have to track which pointer owns dynamic memory manually, but you can often chain a function like this so it converts the return value of a function likestrdup()into an object that owns the memory.You then glue this data structure to other code with something like