Do the ISO C or C++ standards specify `const char *` should be a NULL terminated string?

Viewed 290

I have always seen const char * used in this way, and libc makes assumptions to this effect.

During an API review, I said const char * should be assumed to be a NULL terminated string, then someone said it doesn't have to be - so no assumptions can be made.

We can still be defensive making assumptions, but we can write WAY less code.

Given all the libc functions that use it this way, is there anything in either the C or C++ ISO Standard that says it MUST be a NULL terminated string?

2 Answers

What we can assume about the memory at, or starting at, the address a pointer to const char contains is context dependent.

const charpointers are often used as pointers to ASCII text (a "string"), but don't have to be; such a pointer can as well point to arbitrary data, or to a single char.

APIs which rely on null terminated strings must say so, and they do (e.g. https://linux.die.net/man/3/strcpy).

Do the ISO C or C++ standards specify const char * should be a NULL terminated string?

No, there is no such restriction. As far as the standard is concerned, const char * is just like any other pointer type in this regard. It may point to null, it may point to an array that is not null terminated, it may have an invalid value. All these are implicitly permitted due to not being prohibited.

There are however some standard functions that have const char * parameters and do require that the passed argument is to a null terminated string.

Example:

const char* c1 = nullptr; // c1 is not a null terminated string: allowed
const char arr1[] {'a'};
const char* c2 = arr;     // c2 is not a null terminated string: allowed
{
    const char arr2[] {'\0'};
    c1 = arr2;            // is  a null terminated string: allowed
}  // c1 is invalid: allowed

std::strlen(c1); // not null terminated string: Undefined behaviour
std::strlen(c2); // not null terminated string: Undefined behaviour

Given all the libc functions that use it this way

Not all standard functions require strings to be null terminated. As a rule of thumb, functions that accept a count parameter can be used with non-null terminated arrays as long as the array is at least as long as count.


NULL terminated string

Strings are not terminated by NULL. NULL is a macro that expands to a null pointer constant (or potentially in C, such constant converted to void*). While the null terminator character is not a pointer.

Related