You seem to misunderstand what NUL-termination is useful for. In C, strings can only be represented as sequences of bytes. In order to work with a string, there are two main methods:
- Always know its length, and pass it around every time.
- Do not know its length, but use an unique terminator byte (the NUL byte
\0
), so that any code scanning the string can identify when the end is reached.
Of course, the use of the NUL terminator only applies to strings, and more precisely when dealing with functions that expect the string to be NUL terminated: all standard C library functions do. One could very well write their own library with functions that handle non-NUL-terminated strings though.
If you are dealing with generic char
(or unsigned char
) arrays, there is no need at all to terminate them with NUL, if you do not intend to use them as strings.
In addition to the above, the NUL terminator is implicitly added only for declarations using string literals, like:
char foo[] = "hello";
// foo actually contains 'h' 'e' 'l' 'l' 'o' '\0'
But not when declaring char
arrays:
char foo[] = {'h', 'e', 'l', 'l', 'o'};
// foo actually contains 'h' 'e' 'l' 'l' 'o'
Declaring arrays with initializers smaller than the size of the array has the effect of filling the rest of the slots with zeroes, but that's another story:
char foo[5] = {'h', 'i'};
// foo actually contains 'h' 'i' '\0' '\0' '\0'
Answering your question in the comments:
Lack of NUL termination gives other programmers the opportunity to misuse the variable. Is the opportunity for misuse an issue? I'm gathering from the answers here that it is not.
It is not, so long as you use meaningful names and make sure it's clear that a variable does not represent a string when you do not intend it to.