sprintf_s 导致崩溃
我遇到问题了。 示例:
try
{
char strMes[6];
sprintf_s(strMes, sizeof(strMes), "%s", "012345678");
printf(strMes);
}
catch(...)
{
printf("Wrong\n");
}
在调试环境中,它导致调试器出现“缓冲区太小”消息。
在发布环境中它导致崩溃。
我尝试将 try-catch 块替换为 __try-__ except(EXCEPTION_EXECUTE_HANDLER) 块,但我得到了相同的行为。
我对 sprintf_s 函数有大约 1K 次调用,因此将 sprintf_s 替换为 _snprintf_s 对我来说不是一个选择。 (请参阅缓冲区太小的sprintf_s)
请帮忙!
I meet problem.
Example:
try
{
char strMes[6];
sprintf_s(strMes, sizeof(strMes), "%s", "012345678");
printf(strMes);
}
catch(...)
{
printf("Wrong\n");
}
In debug environment it caused for debugger "buffer too small" message.
In release environment it caused for crash.
I tried to replace try-catch block to __try-__except(EXCEPTION_EXECUTE_HANDLER) block, but I get the same behavior.
I have about 1K callings for sprintf_s function, so replace sprintf_s to _snprintf_s is not option for me. (see sprintf_s with a buffer too small)
Please help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,我相信您应该使用
snprintf
而不是sprintf_s
。其次,CRT 有一个 无效参数处理程序叫。尝试设置一下。
First of all, I believe you should use
snprintf
instead ofsprintf_s
.Second, there is an invalid paramater handler for CRT that gets called. Try setting that.
在进一步使用
strMes
之前,您必须检查sprintf_s
的返回值。否则你怎么知道缓冲区是否足够大?sprintft_s
可能没有向strMes
写入任何内容,因此它仍未初始化。这就是导致崩溃的原因(尝试删除sprintf_s
,它也可能崩溃。)来自
sprintf_s
文档:PS:由于 try/catch,您应该将这个问题标记为 C++ 而不是 C。
You must check the return value of
sprintf_s
before usingstrMes
any further. Otherwise how do you know whether the buffer was big enough?sprinft_s
may have nothing written tostrMes
and so it is still uninitialized. That's what's causing the crash (try removing thesprintf_s
, it likely crashes as well.)From the
sprintf_s
docs:PS: You should tag this question C++ not C due to try/catch.
阅读文档:
默认行为是抛出。您可以覆盖它。
Read the documentation:
The default behaviour is throwing. You can override it.
如果您的 VS 版本支持,您应该对其运行代码分析。
了解关于代码分析
If your VS version supports, you should run Code Analysis on it.
Read about About Code Analysis