计算 sprintf() 缓冲区的大小
(很长一段时间)前,我经常使用以下代码 - 然后在 MSVC 6 上 - 来确定为带有可变参数的函数格式化字符串所需的内存:
void LogPrint(const char *pszFormat, ...)
{
int nBytes;
char *pszBuffer;
va_list args;
va_start(args, pszFormat);
nBytes = vsnprintf(0, 0, pszFormat, va);
va_end(args);
// error checking omitted for brevity
pszBuffer = new char[nBytes + 1];
va_start(args, pszFormat);
vsnprintf(pszBuffer, nBytes, pszFormat, va);
va_end();
// ...
}
在更新版本的 MSVC 中遇到的明显错误(我现在用的是2010)是:
警告 C4996:“vsnprintf”:此函数或变量可能不安全。考虑使用 vsnprintf_s 代替。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。有关详细信息,请参阅联机帮助。
我非常喜欢任何 C(++) 编译器的“将警告视为错误”选项,显然我的构建失败了。对我来说,简单地使用#pragma warning (disable:4996)并继续下去,感觉像是在作弊。
然而,建议的“更安全”替代方案 vsnprintf_s()
是当其“不安全”前身的输入条件发生时,注定会返回-1
。
TL/DR:是否有办法实现 vsnprintf()
的预期行为,以使用其新的、更安全的变体返回完成其任务所需的内存?
编辑:简单地定义_CRT_SECURE_NO_WARNINGS
并不能解决问题;还有很多 strcpy()
到处乱飞。其新版本尚未损坏,因此我仍然希望看到这些。
A (very long) while ago I regularly used the following code - then on MSVC 6 - to determine the memory needed to format a string for a function with variadic arguments:
void LogPrint(const char *pszFormat, ...)
{
int nBytes;
char *pszBuffer;
va_list args;
va_start(args, pszFormat);
nBytes = vsnprintf(0, 0, pszFormat, va);
va_end(args);
// error checking omitted for brevity
pszBuffer = new char[nBytes + 1];
va_start(args, pszFormat);
vsnprintf(pszBuffer, nBytes, pszFormat, va);
va_end();
// ...
}
The obvious error you're getting in a more recent version of MSVC (I'm using 2010 now) is:
warning C4996: 'vsnprintf': This function or variable may be unsafe. Consider using vsnprintf_s instead. To disable deprecation use _CRT_SECURE_NO_WARNINGS. See online help for details.
I'm a big fan of the "treat warnings as errors" option for any C(++)-compiler, and obviously my build fails. It feels like cheating to me to simply employ #pragma warning (disable:4996)
and get on with it.
The suggested "safer" alternative vsnprintf_s()
, however is doomed to return -1
when input conditions of its "unsafe" predecessor occur.
TL/DR: Is there a way to implement the expected behavior of vsnprintf()
to return the memory needed to fulfil its task using the new, safer variants of it?
EDIT: simply defining _CRT_SECURE_NO_WARNINGS
won't cut it; there's a lot of strcpy()
flying around, too. The new variant of which isn't broken, so I'd like to still see these.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您要查看的函数是
_vscprintf
,其中“返回如果使用指定的格式代码打印参数列表指向的字符串或将其发送到文件或缓冲区时将生成的字符数”。还有一个 Widechar 变体 (_vscwprintf
)。The function you want to look at is
_vscprintf
, which "returns the number of characters that would be generated if the string pointed to by the list of arguments was printed or sent to a file or buffer using the specified formatting codes". There's a widechar variant (_vscwprintf
) as well.