您的位置:首页 > 其它

打印字符串的安全函数snprintf

2011-12-01 14:15 211 查看
在读UNIX网络编程时,有这样一段:

“If you're not already in the habit of using snprintf instead of the older
sprintf, now's the time to learn. Calls to
sprintf cannot check for overflow of the destination buffer.
snprintf, on the other hand, requires that the second argument be the size of the destination buffer, and this buffer will not overflow.

snprintf was relatively late addition to the ANSI C standard, introduced in the version referred to as ISO C99. Virtually all vendors provide it as part of the standard C library, and many freely available versions are also available. We use snprintf
throughout the text, and we recommend using it instead of sprintf in all your programs for reliability.

It is remarkable how many network break-ins have occurred by a hacker sending data to cause a server's call to sprintf to overflow its buffer. Other functions that we should be careful with are gets, strcat, and strcpy, normally calling fgets, strncat,
and strncpy instead. Even better are the more recently available function strlcat and strlcpy, which ensure the result is a properly terminated string. Additional tips on writing secure network programs are found in Chapter 23 of [Garfinkel, Schwartz, and
Spafford 2003].”

其主要说的是缓冲区溢出问题,为给缓冲区一个固定的长度,我们需要给这个函数某些限定。

下列代码在VS2005调试通过。

//
// Secure version of SPRINTF function
//
int CSerialPort::snprintf(char *buf, size_t size, const char *fmt, ...)
{
int			n;
va_list		ap;

va_start(ap, fmt);
vsprintf(buf, fmt, ap);
n = strlen(buf);
va_end(ap);
if (n >= size)
TRACE("snprintf: '%s' overflowed array", fmt);

return(n);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: