计算 sprintf() 缓冲区的大小 [英] Calculating the size of an sprintf() buffer

查看:125
本文介绍了计算 sprintf() 缓冲区的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A(很长)前一段时间我经常使用以下代码 - 然后在 MSVC 6 上 - 确定格式化带有可变参数的函数的字符串所需的内存:

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();

    // ...
}

您在更新版本的 MSVC(我现在使用的是 2010)中遇到的明显错误是:

The obvious error you're getting in a more recent version of MSVC (I'm using 2010 now) is:

警告 C4996:vsnprintf":此函数或变量可能不安全.考虑使用 vsnprintf_s 代替.要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS.有关详细信息,请参阅在线帮助.

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.

我是任何 C(++) 编译器的将警告视为错误"选项的忠实粉丝,显然我的构建失败了.对我来说,简单地使用 #pragma warning (disable:4996) 并继续使用它感觉就像在欺骗我.

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.

建议的更安全"替代方案 vsnprintf_s(),但是 当它的不安全"前辈的输入条件发生时,它注定要返回-1.

The suggested "safer" alternative vsnprintf_s(), however is doomed to return -1 when input conditions of its "unsafe" predecessor occur.

TL/DR: 有没有办法实现 vsnprintf() 的预期行为,以使用新的更安全的变体返回完成其任务所需的内存它吗?

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?

简单地定义 _CRT_SECURE_NO_WARNINGS 不会削减它;还有很多 strcpy() 飞来飞去.新变种没有坏,所以我还是想看看这些.

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.

推荐答案

你想看的函数是_vscprintf,其中 " 返回如果打印或发送参数列表指向的字符串将生成的字符数到使用指定格式代码的文件或缓冲区".还有一个宽字符变体(_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.

这篇关于计算 sprintf() 缓冲区的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆