Terminal Null


The terminal null '\0' is a character marking the end of a string in C-style. It is employed by string functions (strlen, strcat) and output functions (sscanf, printf). A terminal null indicates the end of the string being processed at the moment. In other words, the null character serves as an identifier of the end of a string. Without it a sequence of characters can't be processed as a whole string, as the program won't know where it ends.

The examples below show the use of the terminal null.

The first example:

void str_cpy(char* dst, char* src)
{
  while(*dst++ = *src++);
}

In this fragment the value from '*src' is being written into '*dst' until reaching the character '\0'. Once it has been written, the loop terminates.

As the second example, let's examine an implementation of the str_cat(char *to, const char *from) function which unites the strings 'to' and 'from' and outputs the result into 'to'.

void str_cat(char *to, const char *from)
{
  while(*to++);
  to--;
  while (*to++ = *from++);
}

In this example a pointer will be set to the first terminal null found in the 'to' string. After that the program will write the characters from the array 'from' into the array 'to' until reading the terminal null in the 'from' array.

Windows API has structures where pointers to strings must end with two terminal nulls. Such is the member lpstrFilter in the OPENFILENAME structure. lpstrFilter is a pointer to a buffer containing pairs of null-terminated strings for a filter. The first string of a pair contains a filter description (for example, "Text Files"), the second string contains the filter template itself (for example, "*.TXT"). Templates are separated by the terminal null character. The last string in this buffer must end with two nulls.

Here is an example of a string for this parameter from MSDN (2 templates):

ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0"

Each substring ends with a terminal null, including the last one. The compiler will add one more null at the end of the whole string. As a result, there are two terminal nulls at the end so that the function knows the end of the sequence of data being passed.

References


Do you make errors in the code?

Check your code
with PVS-Studio

Static code analysis
for C, C++ and C#

goto PVS-Studio;