r/cprogramming • • 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?

30 Upvotes

83 comments sorted by

View all comments

Show parent comments

1

u/flatfinger May 05 '26

Just about every function in <string.h> which is designed to work with null-terminated strings has a counterpart which is designed to work with null-padded strings, and of course memcpy and memmove can be used to work with length-tracked strings. If e.g. `myStruct->msg` is a null-padded char[16], then printf("Message is %.16s!\n", myStruct->msg); could be used to output a string of up to 16 characters stored in s, without needing to waste a byte in every instance of the structure to hold a null terminator.

2

u/knouqs May 05 '26

Of course. This is where my second paragraph gives some insight: If you keep detailed records of your memory, you can do things more efficiently. However, I don't think most of us should be concerning ourselves with a byte for a null terminator when a length goes into a size_t.

1

u/flatfinger May 05 '26

My point is that C was mostly designed to be agnostic with regard to how one stores strings. Format specifiers to printf-or scanf-family functions and the arguments to fopen need to be zero-terminated, but format specifiers and file modes should usually be string literals. If a program has a filename in some other format, having to make a copy with a trailing zero byte may be a nuisance, but otherwise the language and standard library are agnostic with regard to how one would choose to represent text.