Xref: utzoo comp.lang.c:17048 comp.unix.wizards:15110 Path: utzoo!attcan!uunet!lll-winken!xanth!nic.MR.NET!thor.acc.stolaf.edu!mike From: mike@thor.acc.stolaf.edu (Mike Haertel) Newsgroups: comp.lang.c,comp.unix.wizards Subject: Re: How to predict size of outcome of vsprintf? Keywords: vsprintf formatted conversion Message-ID: <1618@thor.acc.stolaf.edu> Date: 19 Mar 89 18:34:04 GMT References: <993@etnibsd.UUCP> <9872@smoke.BRL.MIL> Reply-To: mike@stolaf.edu Followup-To: comp.lang.c Organization: St. Olaf College, Northfield, MN Lines: 32 In article <9872@smoke.BRL.MIL> gwyn@brl.arpa (Doug Gwyn (VLD/VMB) ) 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 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 In Hell they run VMS.