C strncpy意外输出

c++ strncpy unexpected output

本文关键字:输出 意外 strncpy      更新时间:2023-10-16

我正在查看函数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的缓冲区,而没有任何一个

  1. 指定精确的最大长度(对于 *printf,例如"%15.15S";我找不到C iostreams的直接等效物(或
  2. 在使用NUL之后,明确填充了一个字节,或者保证诸如strncpy(dest,src,len(之类的任何呼叫都将具有strlen(src(&lt; = len-1。
  3. 的先决条件。

当前,您的程序在分配的字符阵列后打印一些未预测的(可能是垃圾(字符,因此,结果是不稳定的,具体取决于平台,编译器,优化级别等,包括系统崩溃的机会和数据丢失的机会:(

对于使用C字符串的更安全的工作,我强烈建议选择一些

  1. strlcpystrlcat(OpenBSD Origin(。
  2. strcpy_s等(c tr(。
  3. 任何具有不含典型警告的阵列和长度结构的方法(甚至使用其string切换到C (。