ISO C 或 C++ 标准是否指定 `const char *` 应该是一个以 NULL 结尾的字符串?
Do the ISO C or C++ standards specify `const char *` should be a NULL terminated string?
我一直看到const char *
是这样使用的,libc
也是这样假设的
在 API 审查期间,我说 const char *
应该被假定为 NULL
终止的字符串,然后有人说它不一定是 - 所以没有假设可以制作。
我们仍然可以进行防御性假设,但我们可以编写更少的代码。
考虑到所有以这种方式使用它的 libc
函数,C 或 C++ ISO 标准中是否有任何内容表明它 必须 是 NULL
终止字符串?
关于指向 const char
的指针所包含的地址或起始地址的内存,我们可以假设的是上下文相关的。
const char
指针经常用作指向 ASCII 文本(“字符串”)的指针,但并非必须如此;这样的指针也可以指向任意数据或单个字符。
依赖空终止字符串的 API 必须如此说明,它们确实如此(例如 https://linux.die.net/man/3/strcpy)。
Do the ISO C or C++ standards specify const char *
should be a NULL terminated string?
不,没有这样的限制。就标准而言,const char *
在这方面与任何其他指针类型一样。它可能指向 null,它可能指向一个不是 null 终止的数组,它可能有一个无效值。由于未被禁止,所有这些都是隐式允许的。
然而,有些标准函数具有 const char *
参数,并且确实要求传递的参数是空终止字符串。
示例:
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[] {'[=10=]'};
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
并非所有标准函数都要求字符串以 null 结尾。根据经验,接受 count
参数的函数可以与非空终止数组一起使用,只要该数组至少与 count
.
一样长
NULL
terminated string
字符串不以 NULL
结尾。 NULL
是一个扩展为空指针常量的宏(或者可能在 C 中,这样的常量转换为 void*
)。虽然空终止符不是指针。
我一直看到const char *
是这样使用的,libc
也是这样假设的
在 API 审查期间,我说 const char *
应该被假定为 NULL
终止的字符串,然后有人说它不一定是 - 所以没有假设可以制作。
我们仍然可以进行防御性假设,但我们可以编写更少的代码。
考虑到所有以这种方式使用它的 libc
函数,C 或 C++ ISO 标准中是否有任何内容表明它 必须 是 NULL
终止字符串?
关于指向 const char
的指针所包含的地址或起始地址的内存,我们可以假设的是上下文相关的。
const char
指针经常用作指向 ASCII 文本(“字符串”)的指针,但并非必须如此;这样的指针也可以指向任意数据或单个字符。
依赖空终止字符串的 API 必须如此说明,它们确实如此(例如 https://linux.die.net/man/3/strcpy)。
Do the ISO C or C++ standards specify
const char *
should be a NULL terminated string?
不,没有这样的限制。就标准而言,const char *
在这方面与任何其他指针类型一样。它可能指向 null,它可能指向一个不是 null 终止的数组,它可能有一个无效值。由于未被禁止,所有这些都是隐式允许的。
然而,有些标准函数具有 const char *
参数,并且确实要求传递的参数是空终止字符串。
示例:
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[] {'[=10=]'};
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
并非所有标准函数都要求字符串以 null 结尾。根据经验,接受 count
参数的函数可以与非空终止数组一起使用,只要该数组至少与 count
.
NULL
terminated string
字符串不以 NULL
结尾。 NULL
是一个扩展为空指针常量的宏(或者可能在 C 中,这样的常量转换为 void*
)。虽然空终止符不是指针。