count_sprintf 的 MSVC/Linux 代码
我需要应该返回的函数 count_sprintf()
在 Win32 和 Linux 上格式化缓冲区所需的字符数(不包括 nul 字节)。
int count_sprintf(const char *format, va_list ap);
当格式化值长于缓冲区大小时,vsnprintf 的返回值在 Win32 与 Linux 之间存在细微差别。这就是我寻求帮助的原因。
你能给出这个函数的可移植代码(#ifdef WIN32)吗?
像这样使用的函数:
int bufsize = 1 + count_snprintf(format, ap);
char *buf = (char*)malloc(bufsize);
vsnprintf(buf, bufsize, format, ap); // on WIN32, _vsnprint, on Linux, vsnprintf.
谢谢
I need function count_sprintf() that should return
number of characters (not inc nul byte) needed for the formatted buffer, on Win32 and on Linux.
int count_sprintf(const char *format, va_list ap);
There are subtle diffs beteen Win32 vs Linux in return value of vsnprintf when formatted value is longer than buffer size. That's why I ask for help.
Can you give portable code (#ifdef WIN32) for this function.
The function to be used like this:
int bufsize = 1 + count_snprintf(format, ap);
char *buf = (char*)malloc(bufsize);
vsnprintf(buf, bufsize, format, ap); // on WIN32, _vsnprint, on Linux, vsnprintf.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
VS 运行时有 _vscprintf 来计算所需的字符数。
The VS runtime has the _vscprintf which counts characters needed.
我不知道你是否想要 C 解决方案、C++ 或两者。
在 C++ 中,有一个非常简单的方法可以解决这个问题:使用流而不是
printf
函数行。在 CI 中,强烈建议您注意使用可变格式字符串的任何情况:如果函数的可变参数稍微偏离一点点,它们很可能会导致问题,并且编译器无法帮助您。如果格式是外部生成的,情况会更糟,因为您基本上对任意数量的缓冲区溢出漏洞持开放态度。至少如果你有一个固定的格式字符串,你知道它从多长开始,并且一些编译器可以对可变参数进行格式字符串检查。
I can't tell if you want a C solution, C++, or both.
In C++ there's an extremely easy way to solve this problem: Use streams instead of the
printf
line of functions.In C I would suggest strongly taking care about any cases where you use a variable format string: They're liable to cause problems if the varargs to the function are even off by a little bit and there's no way for the compiler to help you. If the format is generated externally it's worse as you're basically open to any number of buffer overflow exploits. At least if you have a fixed format string you know how long it will be to start with, and some compilers can do format string checking on the varargs.
在 Linux 上,您可以使用
asprintf
:On Linux you can use
asprintf
:你可以使用 vsnprintf 来实现这一点——如果你给它一个大小为 0 的缓冲区,它实际上不会尝试在缓冲区中放入任何内容,但仍然会返回它要输出的字符数
You can use vsnprintf for this -- if you give it a size 0 buffer, it won't actually try to put anything in the buffer, but will still return the number of characters it would have output