The Null Terminator
One challenge with strings, is that we often need to store strings of varying lengths. For example, the string "Hello, world!"
is 13 characters long, whereas the string "Hello, world, my name is Bob!"
is 27 characters long. If we were to store these strings in a char[]
array, we would need to know the maximum length of the string before we create the array. This is not ideal, as we often don’t know the length of a string before we create it, as the user may enter it at run-time.
There are a few ways to solve this problem, but the simplest is to allocate a block of memory that is large enough to store the largest string we expect to encounter. This is called a statically allocated string. Let’s take a look at a statically allocated string in C/C++:
So great! This program should print out “Hello” to the terminal. Right?!
Well, it will, but we have a problem. How can the C programming language know that the “o” was the final character of that string, if the array has 50 characters? The remaining memory is still allocated to our program and could contain valid characters, or some garbage data.
To get around this issue, the C language decided to add a special terminator character to the string to indicate where it ends.
The null terminator
In C/C++, arrays do not store their lengths, and it is generally up to us as programmers to keep track of how large our arrays are. This is a trade-off, as it allows us to be more efficient with memory, but it also means we need to be more careful when working with arrays.
Because strings are so common, the C/C++ languages have a special way of handling how we can mark the end of a string, and it is by simply introducing a special character called the null terminator (represented by the character \0
). The null terminator is the very first ASCII character at integer 0, and is used to indicate the end of the string. It does not get printed to the terminal, but tells any code working with the array to stop there. Let’s take a look at how we can use the null terminator to solve our problem:
This program should print out “Hello”, and printf will know that the string ends when it gets to the '\0'
after the “o”!
The great news is that string constants automatically include the extra null terminator, so “Hello” is 6 characters. The five we can see, and the null terminator.
C also include shorthand ways to initialise strings using string constants, which therefore automatically add the null terminator for us:
The above program will automatically have a null terminator added to the end of the string!