当我们在C的字符串末尾不包含'\ 0'时会发生什么? [英] What happened when we do not include '\0' at the end of string in C?
问题描述
在C中,当我以这种方式初始化数组时:
In C, when I initialize my array this way:
char full_name[] = {
't', 'o', 'a', 'n'
};
并用printf("%s", full_name);
并使用 valgrind 运行它
未初始化的值是通过堆栈分配创建的
Uninitialised value was create by stack allocation
为什么会这样?
推荐答案
由于%s
格式说明符期望以空字符结尾的字符串,因此代码的结果行为是不确定的.您的程序被认为是格式错误的,可以完全不产生任何输出,不产生任何输出,崩溃等.简短地说,不要那样做.
Since %s
format specifier expects a null-terminated string, the resulting behavior of your code is undefined. Your program is considered ill-formed, and can produce any output at all, produce no output, crash, and so on. To put this shortly, don't do that.
这并不是说所有字符数组都必须以空字符结尾:该规则仅适用于打算用作C字符串的字符数组,例如可以传递给%s
格式说明符上的printf
,或者传递给strlen
或Standard C库的其他字符串函数.
This is not to say that all arrays of characters must be null-terminated: the rule applies only to arrays of characters intended to use as C strings, e.g. to be passed to printf
on %s
format specifier, or to be passed to strlen
or other string functions of the Standard C library.
如果打算将char
数组用于其他用途,则无需将其终止为null.例如,此用法已完全定义:
If you are intended to use your char
array for something else, it does not need to be null terminated. For example, this use is fully defined:
char full_name[] = {
't', 'o', 'a', 'n'
};
for (size_t i = 0 ; i != sizeof(full_name) ; i++) {
printf("%c", full_name[i]);
}
这篇关于当我们在C的字符串末尾不包含'\ 0'时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!