How to predict size of outcome of vsprintf?

Steve Summit scs at adam.pika.mit.edu
Tue Mar 21 15:23:23 AEST 1989


[Apologies if you see this twice; is there a known problem with
canceling cross-posted articles under nntp?]

In article <28831 at bu-cs.BU.EDU> bzs at bu-cs.BU.EDU (Barry Shein) writes:
>Another way to say that is:
>	print_width = LOGx(N) + 1
>where x (the log base) is the base to be printed in...

An occasionally-useful observation is that an upper bound on this
value is something like 8*sizeof(int), which is the number of
characters it could take to print an int in base 2 (some printf's
even provide %b for this purpose!).  As Barry noted, this helps
only in the simplest cases.  (I use it internally to my own
version of printf, for the buffer size in which integer conversion,
before padding, is performed.  Unfortunately, the assumption that
sizeof deals in 8-bit units is not perfectly valid.)


In article <1618 at thor.acc.stolaf.edu> mike at stolaf.edu writes:
>The (unreleased) GNU C library contains routines something like:
>	int snprintf(char *str, size_t len, const char *fmt, ...);
>	int vsnprintf(char *str, size_t len, const char *fmt, va_list ap);
>that do bounds checking on their output.
>I also recall a posting by Chris Torek a few
>months ago that [mentioned] a routine that looked something like:
>	FILE *fmemopen(void *mem, size_t len, const char *how);
>This solves the same problem, and offers additional advantages as well.

My own soon-to-be-released stdio replacement contains

	char *smprintf(char *fmt, ...)

which returns a malloc'ed pointer to an area of memory just big
enough for the formatted string.  (snprintf only allows you to
prevent overflow of a finite-sized buffer; smprintf lets the
resultant buffer be as big as it needs to be.)  I may also add

	FILE *strmopen();
	char *strmclose(FILE *);

which would give you a fd on which you could do arbitrary stdio
output, dynamically allocating (and reallocating as needed) an
in-memory buffer, the eventual pointer to which would be returned
by strmclose.  (I've got to think of better names for these; the
'm' is supposed to stand for "malloc" but the overall effect ends
up sounding like "stream" which is misleading.)

[Exercise for the student: implement smprintf in terms of
strmopen, vfprintf, and strmclose.]

                                            Steve Summit
                                            scs at adam.pika.mit.edu



More information about the Comp.unix.wizards mailing list