Enno
Enno

Reputation: 1862

Visual C++ _snprintf setting errno to ERANGE

I just noticed that when my code is compiled with Visual C++ 2013, the _snprintf function sets errno to ERANGE (Result too large) when the destination buffer is too small. This doesn't seem to be documented: https://msdn.microsoft.com/en-us/library/2ts7cx93.aspx

I expect a return value of -1 (and so did the code), but not any meddling with errno. Is this behavior docuemnted elsewhre, and is it possibly a recent change? Does the C++11 standard (which I believe adds snprintf) have anything to say about this?

Upvotes: 3

Views: 352

Answers (2)

Floyd Barbary
Floyd Barbary

Reputation: 11

The function is in compliance with the standard. As mentioned by Tomasz, the complete text of 7.5.3 says " The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard". The use of errno is not documented in the description of sprintf in the Standard, ergo the library is free to set errno to a non-zero value. Whether Microsoft documents something or not in their documentation is not covered by 7.5.3.

Upvotes: 1

Tomasz Sodzawiczny
Tomasz Sodzawiczny

Reputation: 347

Does the C++11 standard (which I believe adds snprintf) have anything to say about this?

Yes, the behaviour you described would be correct for snprintf. After the C standard (referred to by C++ standard):

(7.21.6.5.3.) The snprintf function returns the number of characters that would have been written had n been sufficiently large, not counting the terminating null character, or a negative value if an encoding error occurred. Thus, the null-terminated output has been completely written if and only if the returned value is nonnegative and less than n.

As for the errno - the function description says nothing about it, so this applies:

(7.5.3.) The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard.

Upvotes: 3

Related Questions