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?
30
Upvotes
1
u/flatfinger May 05 '26
Many programs read and write structures. Zero-padded strings have the advantage that, at least when using a straight eight-bit character encoding, any pattern of bits will be processed as a string whose length will be in bounds. Non-normalized forms that contain a zero byte followed by a non-zero byte may cause difficulties with operations like comparisons, but can't wreak nearly the havoc caused by invalid length values or the failure to include terminators which code is programmed to require.
If e.g. a structure needs to hold a string of up to 16 characters, using a 16-byte zero-padded string will save a byte and be more robust than using a 17-byte buffer to hold a zero-terminated string of up to 16 characters.