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 comment

1

u/BatchModeBob May 05 '26

If an attacker can change your memory you're SOL no matter what you do. The attacks that make the news are when unexpected data breaks your code. Suppose you have char buffer [100] to process input from a URL. The attacker can make a much longer URL and send it to you. When your code does strcpy (buffer, URL), it writes past the end of buffer. Classic buffer overrun. In the simplest exploitable case, the overrun will overwrite code that gets executed later. So the hacker chooses his special URL characters to be the opcodes he wants your code to execute.

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.

-1

u/arihoenig May 05 '26

Attackers can always change your memory, so that is just something that has to be accepted. Also for pure reliability, high energy photons can also change that null to a non null.