How to predict size of outcome of vsprintf?

Mike Haertel mike at thor.acc.stolaf.edu
Mon Mar 20 04:34:04 AEST 1989


In article <9872 at smoke.BRL.MIL> gwyn at brl.arpa (Doug Gwyn (VLD/VMB) <gwyn>) writes:
>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).
>
...
>
>Don't use *sprintf() when you can't be sure that the output length
>will be small enough.  Seriously.

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.  Richard Stallman suggested to
ANSI that they include such routines in the C standard; I am of the
impression that various other people independently made the same or a
similar suggestion.  I also recall a posting by Chris Torek a few
months ago that included an excerpt from a <stdio.h> that included
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.

I do not understand why the pANS does not address this problem in some way.
-- 
Mike Haertel <mike at stolaf.edu>
In Hell they run VMS.



More information about the Comp.unix.wizards mailing list