strncpy是比strcpy更安全的字符串拷贝函数,但在使用中需要注意一点:
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).
如果在strncpy后不显式追加'\0',那么你不可直接把它当做字符串使用处理,不然可能会出现乱码,甚至程序奔溃。
追加下strncpy glibc的实现版本
char *
STRNCPY (char *s1, const char *s2, size_t n)
{
char c;
char *s = s1;
--s1;
if (n >= 4)
{
size_t n4 = n >> 2;
for (;;)
{
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
c = *s2++;
*++s1 = c;
if (c == '\0')
break;
if (--n4 == 0)
goto last_chars;
}
n = n - (s1 - s) - 1;
if (n == 0)
return s;
goto zero_fill;
}
last_chars:
n &= 3;
if (n == 0)
return s;
do
{
c = *s2++;
*++s1 = c;
if (--n == 0)
return s;
}
while (c != '\0');
zero_fill:
do
*++s1 = '\0';
while (--n > 0);
return s;
}