我正在阅读这篇文档,它说:
char *strncpy(char *destination, const char *source, size_t num);
Copy characters from string Copies the first
num
characters ofsource
todestination
. If the end of thesource
C string (which is signaled by a null-character) is found beforenum
characters have been copied,destination
is padded with zeros until a total ofnum
characters have been written to it.No null-character is implicitly appended at the end of destination if source is longer than
num
. Thus, in this case,destination
shall not be considered a null terminated C string (reading it as such would overflow).
destination
andsource
shall not overlap (seememmove
for a safer alternative when overlapping).
但是我对这个声明感到困惑:
在这种情况下,目标不应被视为以空结束的C字符串(如果将其视为这样,会造成缓冲区溢出)
由于如果 num > strlen(source)
,它将在末尾填充 '\0'
,'\0'
实际上是一个字符串中的空字符(终止符),那么为什么它不应该被视为以空结束的 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);
以下输出结果是正常的:
from hello
to hello
strncpy
:不要使用它。 - chqrlie'\0'
是导致strlen(source) > num
的原因,所以我认为你只是有一个简单的误解 - 尝试使用strncpy(to, from, 2);
。 - Ken Y-N