When and why can sprintf fail?

Posted by Srekel on Stack Overflow See other posts from Stack Overflow or by Srekel
Published on 2010-06-01T08:50:14Z Indexed on 2010/06/01 8:53 UTC
Read the original article Hit count: 241

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about c