How to predict size of outcome of vsprintf?

Paul Sander paul at athertn.Atherton.COM
Tue Mar 21 13:08:00 AEST 1989


I seem to have missed the original posting, so I'll follow up Doug Gwyn's
followup...

In article <9872 at smoke.BRL.MIL>, gwyn at smoke.BRL.MIL (Doug Gwyn ) writes:
> In article <993 at etnibsd.UUCP> sean at etnibsd.UUCP (Sean McElroy) writes:
> >O.K. Unix/C gurus, since vsprintf requires the user to ensure that there
> >is enough space in the output string, how does one predict the size of
> >the output string?  Is there a routine which returns the predicted
> >length of the output string (effectively preforming the printf conversions)
> >without actually producing the output string?
> 
> No.  Sometimes you can accurately predict an upper bound on the output
> string length; for example if the format is "%d" and the numerical
> argument is known to lie between 0 and 5000, the maximum number of
> characters for the *sprintf() output will be 5 (including the null
> byte at the end).
> 
> >Any suggestions welcome.
> 
> Don't use *sprintf() when you can't be sure that the output length
> will be small enough.  Seriously.

My guess is that Sean wants to malloc enough space for his output, since
he doesn't know how long it is.  I like to do that from time to time myself
when I have to copy user data (which I have very little control over) into
an array of strings that I display later (e.g., in a scrollpane).

So far, I've been lucky in that my data are usually displayed in some
fixed format, followed by a variable length string.  Calculating the length
of *sprintf is easy in this case (at least in a platform- and application-
dependent way) by summing the ceilings of the lengths of the fixed part of 
the output, and adding the strlen of the variable length part (plus 1 for
the null).

It seems to me that it should be possible to write a printf-like function 
that scans the format string and remaining arguments, returning the
ceiling of the length of the result of the *sprintf.

I realize that this problem can only be solved on a platform-by-platform
basis, but thisseems like a fundamental enough problem that someone somewhere 
must have done it for some platforms.  Has anyone tried?
-- 
Paul Sander        (408) 734-9822       | Do YOU get nervous when a
paul at Atherton.COM                       | sys{op,adm,prg,engr} says
{decwrl,sun,hplabs!hpda}!athertn!paul   | "oops..." ?



More information about the Comp.unix.wizards mailing list