- snprintf 与 sprintf函数比较
extern int snprintf (char *__restrict __s, size_t __maxlen, __const char *__restrict __format, ...)
snprintf 保证缓冲区不会发生越界情况。第二个参数maxlen要求目标缓冲区大小,确保不会发生缓冲区溢出现象。
sprintf不保证缓冲区溢出,只是将from信息复制到to缓冲区,容易造成溢出,软件容易被黑客攻击。
- strcpy、strncpy和strlcpy函数比较
extern char *strcpy (char *__restrict __dest, __const char *__restrict __src) __THROW __nonnull ((1, 2));
strcpy 将src信息复制到dest缓冲区中,不保证缓冲区溢出。
extern char *strncpy (char *__restrict __dest,__const char *__restrict __src, size_t __n)__THROW __nonnull ((1, 2));
strncpy保证缓冲区不会发生越界情况,第三个参数n是指定src可以输入的最大长度,但是strncpy并不保证添加'/0'。例如strncpy(dest,"abc",3);只是将abc服知道dest中并不添加'/0'。如果n大于输入长度则会在末尾添加'/0'。
良好的写法如下:
#define MAXLEN(s) (sizeof(s)/sizeof(s[0])-1)
void Strncpy(char *pcDest, char *pcSrc, size_t n)
{
strncpy(pcDest, pcSrc, min(n, MAXLEN(t)));
}
strlcpy相比于strcpy、strncpy更加安全并且会自动添加'/0'。但是目前还不是标准。strlcpy的标准代码附加如下:
size_t CPppStats::strlcpy(char *dst, const char *src, size_t siz) const
{
char *d = dst;
const char *s = src;
size_t n = siz;
// Copy as many bytes as will fit
if ( (n != 0) && (--n != 0) )
{
do
{
if ( (*d++ = *s++) == 0 )
{
break;
}
} while (--n != 0);
}
// Not enough room in dst, add NUL and traverse rest of src
if ( n == 0 )
{
if ( siz != 0 )
{
*d = '/0'; // NUL-terminate dst
}
while (*s++)
{
;
}
}
return(s - src - 1); // count does not include NUL
}
- strcat和strncat函数比较同上不述。