Linux Programmer's Manual STRCPY(3) NAME strcpy, strncpy - copy a string SYNOPSIS #include <string.h> char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); DESCRIPTION The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null terminated. If the length of src is less than n, strncpy() pads the remainder of dest with null bytes. A simple implementation of strncpy() might be: char* strncpy(char *dest, const char *src, size_t n){ size_t i; for (i = 0 ; i < n && src[i] != '\0' ; i++) dest[i] = src[i]; for ( ; i < n ; i++) dest[i] = '\0'; return dest; }
最后一句:
"If the length of src is less than n, strncpy() pads the remainder of dest with null bytes. "
也就是说,strncpy并不仅仅是做一个n长度的保护,而会把剩下的字符清为0x00。要知道,snprintf()是没这档子事情的。所以,我们要记住:
snprintf()总是比sprintf()安全,但是strncpy()和strcpy()比就不一定了。
strcpy()是依据源串的\0作为结束判断的,不检查copy先的Buffer的Size,如果目标空间不够,就有BufferOverflow问题。
转自:http://xzpeter.blog.51cto.com/783279/329052