c strncpy null是否终止

bee*_*lej 2 c strncpy

我正在阅读这份文件,它说:

char *strncpy(char *destination, const char *source, size_t num);
Run Code Online (Sandbox Code Playgroud)

从字符串复制的字符复制第一num的人物sourcedestination.如果在复制字符source之前找到C字符串的末尾(由空字符表示)num,destination则用零填充,直到num写入总共字符为止.

如果source长于,则不会在目标末尾隐式附加空字符num.因此,在这种情况下,destination不应将其视为空终止的C字符串(读取它会溢出).

destination并且source不得重叠(重叠时参见memmove更安全的替代方案).

但我对此声明感到困惑:

在这种情况下,目标不应被视为空终止的C字符串(读取它会溢出)

因为if num > strlen(source),它将'\0'在最后填充,'\0'实际上是字符串中的空(终止)字符,为什么它不应被视为以null结尾的C字符串?

我写了下面的代码来验证:

  char from[] = { 'h', 'e', 'l', 'l', 'o', '\0' };
  char to[1024];
  for (int i = 0; i < 1024; i++) {
      to[i] = 'e';
  }
  strncpy(to, from, 1024);
  printf("from %s\n", from);
Run Code Online (Sandbox Code Playgroud)

它适用于以下输出:

from hello
to hello
Run Code Online (Sandbox Code Playgroud)

Spa*_*key 6

这是在谈论strlen(source)> 时的情况num.它只会复制num字符,其中没有一个是NUL,也不会添加NUL.


G. *_*pen 5

strncpy(dst, src, len)dst如果src在第一个len字节中有一个空终止符,则只添加一个空终止符.您的代码似乎有效,因为数组后可能有也可能没有空字符to[].更好的测试是:

char source[] = "source";
char dest[] = "destination";
strncpy(dest, source, 6);
printf("%s\n", dest);
Run Code Online (Sandbox Code Playgroud)

结果应该是:

sourceation
Run Code Online (Sandbox Code Playgroud)

如果你改写strncpy(dest, source, 7),那么输出只是单词source.