When and why can sprintf fail?

I use swprintf to create a string in a buffer (using a loop by the way).

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 statement never hits, can I be sure that it will never get into live code? That is, do I need to check if nWritten is <0 and handle this, or can I safely assume that there will be no problems?

Under what circumstances can it return -1? The documentation more or less simply says: "If the function does not work." In one place, I read that he will fail if he cannot match the arguments (i.e. the format string with varargs), but that doesn't bother me.

I also do not worry about buffer overflows in this case - I know that the buffer is large enough.

+4
source share
4 answers

From c99 standard:

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

This usually only happens with multibyte and wide character set functions.

+4
source

This may be unsuccessful with the wrong format string, for example, which cannot happen in your case.

If the buffer is not large enough, it can.

Otherwise, there is no reason for refusal.

+2
source

On UNIX, it may fail:

  EILSEQ A wide-character code that does not correspond to a valid character has been detected. EINVAL There are insufficient arguments. 

EILSEQ has already been mentioned.

It may also fail, SIGSEGV, when the format specifier does not match the data - an example using the% s format specifier with an example of 32 bits:

 int pdq=0xffffffff; char tmp[32]={0x0}; sprintf(tmp, "%s", pdq); 
+2
source

I believe that there is another case where snprintf () cannot be successful. It does not seem to be mentioned in POSIX or in the current Linux man page.

After successful completion, the function snprintf () should return the number of bytes that would be written to s, was large enough, excluding the terminating null byte.

snprintf () returns an int . But the input string may be larger than INT_MAX .

+2
source

Source: https://habr.com/ru/post/1311494/


All Articles