Boost logo

Boost :

From: Ben Hutchings (ben.hutchings_at_[hidden])
Date: 2004-10-25 08:17:11


Caleb Epstein wrote:
> On Sat, 23 Oct 2004 07:10:48 +0000 (UTC), Darryl Green
> <darryl.green_at_[hidden]> wrote:
>
>
>> char buf[101];
>> va_list args;
>> va_start(args, fmt);
>> int n = vsnprintf (buf, 101, fmt, args));
>> va_end(args);
>> if (n < 0) return;
>
>
> This is one of the reasons I find the *snprintf functions to be pure
> evil. They don't return -1 when the output would be too long, they
> return the size they WOULD have written if the buffer was large
> enough.

That's not evil; it's extremely useful if you want to dynamically
allocate a large enough buffer. All you have to do is check that the
return value is less than or equal to the length you passed in.

(Aside: what if the length is greater than INT_MAX?)

> Is this code doing what you intend?

When built with Visual C++, it probably is. MS documents this function
as returning a negative value in case of error. A portable test would
be size_t(n) > sizeof(buf).

Ben.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk