C strncpy意外输出
c++ strncpy unexpected output
我正在查看函数strncpy的字符串操纵函数。我得到7个输出而不是3个输出,有人可以解释吗?非常感谢。
char x[] = "just see that.";
char y[15];
char z[10];
char l[14];
strcpy(y, x);
cout << "The string in array x is: " << x
<< "n The string in array y is: " << y << 'n';
strncpy(z, x, 9);
z[9] = 'n';
cout << "The string in array z is: " << z << endl;
strncpy(l, x, 13);
l[13] = 'n';
cout << "The string in array l is: " << l<< endl;
输出有7行,如下
The string in array x is: just see that.
The string in array y is: just see that.
The string in array z is: just see
just see that.
The string in array l is: just see that
just see
just see that.
如果要终止终止,则应使用' 0'而不是' n'
z[9] = 'n'
或l[13] = 'n'
字符串未终止。因此,打印它们可能会导致读取范围和未定义的行为。
strncpy
非常具体,即如果您指定较小或等于源字符串长度,则不会自动终止(使用NUL
== ' '
(目标缓冲区。OTOH如果源字符串甚至较短(LEN-2或更少(,它将填充更多的目标缓冲区字节。最初,strncpy
的设计是为了补充用于外部I/O的缓冲区,因此可以比较精确的字节数,而无需检测到NUL。它不是不是用于"通常"字符串操纵的"方便"功能,并且不得用于此目标。
结果,您应打印一个带有strncpy
的缓冲区,而没有任何一个
- 指定精确的最大长度(对于 *printf,例如"%15.15S";我找不到C iostreams的直接等效物(或
- 在使用NUL之后,明确填充了一个字节,或者保证诸如strncpy(dest,src,len(之类的任何呼叫都将具有strlen(src(&lt; = len-1。 的先决条件。
当前,您的程序在分配的字符阵列后打印一些未预测的(可能是垃圾(字符,因此,结果是不稳定的,具体取决于平台,编译器,优化级别等,包括系统崩溃的机会和数据丢失的机会:(
对于使用C字符串的更安全的工作,我强烈建议选择一些
-
strlcpy
,strlcat
(OpenBSD Origin(。 -
strcpy_s
等(c tr(。 - 任何具有不含典型警告的阵列和长度结构的方法(甚至使用其
string
切换到C (。
相关文章:
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 字符串比较中的意外输出
- 每次在 c++ 中输出不同(意外行为)
- 来自 decltype 的意外输出类型
- 字符数组到十六进制字符串的转换 - 意外输出
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用后序遍历递归的深度优先搜索会产生意外输出
- C++的意外输出
- 标准输出C++意外行为
- 贝金纳C++练习解决方案的意外输出
- 无效* 转换获得意外输出
- 以下程序的意外输出
- 意外输出:矢量矢量(功率集)
- 基本 int 数组提供意外输出
- 线程的意外输出
- 减法中的意外输出
- 带有左移操作员C 的意外输出
- C strncpy意外输出
- 意外输出..函数绑定在虚拟表中的发生方式
- 星号的意外输出