繁体   English   中英

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终止的字符串?

我们可以假设 memory 位于或开始于指向const char的指针包含的地址取决于上下文。

const char指针通常用作指向 ASCII 文本(“字符串”)的指针,但并非必须如此; 这样的指针也可以指向任意数据或单个字符。

依赖于 null 终止字符串的 API 必须这样说,而且它们确实如此(例如https://linux.die.net/man/3/strcpy )。

ISO C 或 C++ 标准是否指定const char *应该是 NULL 终止的字符串?

不,没有这样的限制。 就标准而言, const char *在这方面与任何其他指针类型一样。 它可能指向 null,它可能指向一个不是 null 终止的数组,它可能具有无效值。 由于没有被禁止,所有这些都是隐式允许的。

但是,有些标准函数具有const char *参数,并且确实要求传递的参数是 null 终止的字符串。

例子:

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

鉴于所有以这种方式使用它的 libc 函数

并非所有标准函数都要求字符串以 null 终止。 根据经验,接受count参数的函数可以与非空终止的 arrays 一起使用,只要数组至少与count一样长。


NULL终止字符串

字符串不会被NULL终止。 NULL是一个宏,可扩展为 null 指针常量(或可能在 C 中,此类常量转换为void* )。 而 null 终止符不是指针。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM