sprintf 何时以及为什么会失败? [英] When and why can sprintf fail?

查看:78
本文介绍了sprintf 何时以及为什么会失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 swprintf 将字符串构建到缓冲区中(使用循环等).

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';

如果在测试期间断言从未命中,我能确定它永远不会在实时代码中命中吗?也就是说,我是否需要检查 nWritten <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?

什么情况下可以返回-1?文档或多或少只是说明如果功能失败".在一个地方,我读到如果它不能匹配参数(即格式化字符串到可变参数),它将失败,但这并不让我担心.

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.

推荐答案

来自 c99 标准:

sprintf 函数返回写入数组的字符数,不计算终止空字符,如果发生编码错误,则返回负值.

The sprintf function returns the number of characters written in the array, not counting the terminating null character, or a negative value if an encoding error occurred.

这通常只发生在多字节和宽字符集函数中.

This generally happens only with the multi-byte and wide character character set functions.

这篇关于sprintf 何时以及为什么会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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