Theo de Raadt wrote:
I'm having trouble making snprintf return -1. I've tried stuff like:len = snprintf(str, 0, "%.-Z\n", 9); printf("%d", len); but that just prints `2'. Does snprintf ever return -1?
The "new" snprintf() returns -1 on ``output or encoding error'', as was explained. Luckily, that's almost always the case in relatively recent Unix-land (where currently available.)
The "old" one, including the one in MS Windows (just in case you need to be very portable (painful)), always returns -1 on error or truncation -- i.e. you can't use it to count the chars that would've been written if enough space was available on those systems. At least Windows offers _vscprintf() to count chars, but well ... *blegh*. Just in case you ever feel like re-implementing a poor-man's (but portable) asprintf() for something with vsnprintf().
Anyways, just felt like sharing this, since I've been digging in this stuff for a while recently. :-/
You must check for either ret > buflen or ret == -1 being a failure condition.
Or, if you don't care about the destinction between truncation and encoding/output error, you can check for (ret < 0 || ret > buflen), which takes care of the unlikely case of snprintf() overflowing its return int. Or do both. Just in case ... like, some freak accident when a >2GB string might be supplied to you. ;P
Moritz

