sprintf 何时以及为何会失败?
我正在使用 swprintf 将字符串构建到缓冲区中(使用循环等)。
const int MaxStringLengthPerCharacter = 10 + 1;
wchar_t* pTmp = pBuffer;
for ( size_t i = 0; i < nNumPlayers ; ++i)
{
const int nPlayerId = GetPlayer(i);
const int nWritten = swprintf(pTmp, MaxStringLengthPerCharacter, TEXT("%d,"), nPlayerId);
assert(nWritten >= 0 );
pTmp += nWritten;
}
*pTaskPlayers = '\0';
如果在测试过程中断言从未命中,我能否确定它永远不会在实时代码中命中?也就是说,我是否需要检查 nWritten < 0 并处理这个问题,或者我可以放心地假设不会有问题吗?
什么情况下可以返回-1?文档或多或少只是说明“如果功能失败”。在一个地方我读到,如果它不能匹配参数(即可变参数的格式化字符串),它将失败,但这并不让我担心。
在这种情况下,我也不担心缓冲区溢出 - 我知道缓冲区足够大。
I'm using swprintf to build a string into a buffer (using a loop among other things).
const int MaxStringLengthPerCharacter = 10 + 1;
wchar_t* pTmp = pBuffer;
for ( size_t i = 0; i < nNumPlayers ; ++i)
{
const int nPlayerId = GetPlayer(i);
const int nWritten = swprintf(pTmp, MaxStringLengthPerCharacter, TEXT("%d,"), nPlayerId);
assert(nWritten >= 0 );
pTmp += nWritten;
}
*pTaskPlayers = '\0';
If during testing the assert never hits, can I be sure that it will never hit in live code? That is, do I need to check if nWritten < 0 and handle that, or can I safely assume that there won't be a problem?
Under which circumstances can it return -1? The documentation more or less just states "If the function fails". In one place I've read that it will fail if it can't match the arguments (i.e. the formatting string to the varargs) but that doesn't worry me.
I'm also not worried about buffer overrun in this case - I know the buffer is big enough.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自c99标准:
这种情况通常仅发生在多字节和宽字符字符集函数中。
From the c99 standard:
This generally happens only with the multi-byte and wide character character set functions.
例如,它可能会因格式字符串错误而失败,这在您的情况下不会发生。
如果缓冲区不够大,也可以。
否则,没有理由失败。
It may fail with wrong format string, for example, which cannot happen in your case.
If buffer is not big enough, it may.
Otherwise, no reason for it to fail.
在 UNIX 中,它可能会失败:
EILSEQ 已经提到过。
当格式说明符与数据不匹配时,它也可能会失败,SIGSEGV - 例如使用 %s 格式说明符和 int、32 位示例:
In UNIX, it can fail:
EILSEQ has already been mentioned.
It may also fail, SIGSEGV, when the format specifier does not match the data - example using a %s format specifier with an int, 32 bit example:
我相信还有另一种情况 snprintf() 无法成功。 POSIX 或当前的 Linux 联机帮助页中似乎没有提及它。
snprintf() 返回
int
。但输入字符串可能大于INT_MAX
。I believe there is another case where snprintf() cannot succeed. It does not appear to be mentioned in POSIX or the current Linux manpage.
snprintf() returns
int
. But an input string could be larger thanINT_MAX
.