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.
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.
From the c99 standard:
This generally happens only with the multi-byte and wide character character set functions.
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
.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: