Boost logo

Boost :

From: Caleb Epstein (caleb.epstein_at_[hidden])
Date: 2004-10-25 08:57:17


On Mon, 25 Oct 2004 14:17:11 +0100, Ben Hutchings
<ben.hutchings_at_[hidden]> wrote:
> 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).

OK, perhaps it isn't *pure* evil, but I have seen lots of code that
assumes *snprintf returns -1 when the buffer is too small. It
doesn't, or at least not portably.

I just think this behavior is confusing w/r/t the behavior of other
standard library functions and leads to subtle program bugs, which is
why I dislike this family of functions.

-- 
Caleb Epstein
caleb.epstein_at_[hidden]

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