“snprintf_s”的错误安全感
MSVC 的“安全”sprintf
函数有一个模板版本,它“知道”目标缓冲区的大小。然而,这段代码在字节
结束后很高兴地在堆栈上绘制了567890...
char bytes[5];
_snprintf_s( bytes, _TRUNCATE, "%s", "1234567890" );
知道我做错了什么,还是这是一个已知的错误?
(我在 VS2005 中工作 - 没有在 2008 年或 2010 年进行测试)
MSVC's "secure" sprintf
funcions have a template version that 'knows' the size of the target buffer. However, this code happily paints 567890 over the stack after the end of bytes
...
char bytes[5];
_snprintf_s( bytes, _TRUNCATE, "%s", "1234567890" );
Any idea what I do wrong, or is this a known bug?
(I'm working in VS2005 - didn't test in 2008 or 2010)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它似乎确实是一个错误在 Visual C++ 2005 中(我无法访问该链接;Google 也对其进行了缓存)。
我能够在 Visual C++ 2005 中重现该问题。在 Visual C++ 2008 和 2010 中,字符串被正确截断(
bytes
包含1234\0
)并且- 1
按预期返回。It does appear to be a bug in Visual C++ 2005 (I'm having trouble getting to that link; Google also has it cached).
I was able to reproduce the problem in Visual C++ 2005. In Visual C++ 2008 and 2010, the string is correctly truncated (
bytes
contains1234\0
) and-1
is returned as expected.这个例子确实是正确的。截至版本 --
-- 包括 SP1、vista 修补程序和一些库修补程序 --
上面提到的函数
仍然有问题。然而,真正令人着迷的是,只有 4 个变体中的这个函数
int _snprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, :::
templateint _snprintf_s(char (&buffer)[size], size_t count, :::
int _snwprintf_s
(宽字符版本)templateint _snwprintf_s
(是的,宽字符版本可以)是有问题的,也就是说,如果使用非模板版本,则可以,如果使用任一宽字符版本也不错。
The example is indeed correct. As of version --
-- which includes SP1, the vista hotfix and a few of the library hotfixes --
the above mentioned function
still is buggy. However, what is really fascinating is that only this function of the 4 variant functions
int _snprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, :::
template <size_t size> int _snprintf_s(char (&buffer)[size], size_t count, :::
int _snwprintf_s
(wide character version)template <size_t size> int _snwprintf_s
(yes, the wide character version is OK)is buggy, that is if one's using the non-template version it's OK, and if one's using either of the wide character versions it's OK too. Amazing.
例子错了。
代码应该是:
对于错误的代码,可能是编译器没有给出任何警告的错误,但它是对 snprintf 的弱检查。
Example was wrong.
The code should be:
For the wrong code, it may a bug that the compiler did not give any warning but it would be the weak checking for snprintf.