Path: utzoo!attcan!uunet!auspex!guy From: guy@auspex.UUCP (Guy Harris) Newsgroups: comp.lang.c Subject: Re: gets(3) nonsense Message-ID: <502@auspex.UUCP> Date: 23 Nov 88 21:56:43 GMT References: <867@cernvax.UUCP> <645@quintus.UUCP> <339@igor.Rational.COM> <14447@mimsy.UUCP> <1643@solo11.cs.vu.nl> <1403@unisoft.UUCP> <644@scotty.UUCP> Reply-To: guy@auspex.UUCP (Guy Harris) Organization: Auspex Systems, Santa Clara Lines: 43 >What about sprintf() & fprintf()? >The user does not have *complete control* over these functions. "fprintf()" is, as stated in another article, irrelevant; if the buffer fills up, the standard I/O library will generally write it out and continue. As for "sprintf": Users do have control over the format operations they use with these functions. The "%d", "%i", "%o", "%u", "%x", "%X", "%e", "%E", "%f", "%g", and "%G" conversions, and their "l"-prefixed equivalents (and "h"-prefixed and "L"-prefixed equivalents, in the dpANS upon which K&R Second Edition is based), have, on most implementations, a maximum length of output that they can generate; you can probably pick a number that's "big enough" for all implementations you're likely to run into (e.g., "%d" is unlikely to produce more digits than are in -2^64 - the "-" is for the minus sign" and is extremely unlikely to produce more digits than are in -2^128). "%s" can take a "precision" argument that specifies the *maximum* number of characters to be produced. "%c" only produces one character. The only tricky one appears to be the dpANS's "%p", and you can probably, in most implementations, just say something like "it's unlikely to produce more than 128 characters"; if a pointer value takes 128 characters to dump, you may want to consider not dumping it.... Thus, if you don't use "%s" by itself, you can compute a "maximum length" for the output of "sprintf" that should work, as stated, on most implementations. If you do use "%s" by itself, you do at least have control over what argument matches it, so you can use "strlen" to find out how many characters it will generate. If the format string is generated at run time (e.g., inside an interpreter for a programming language that includes a "printf" construct), you can consider scanning the string, computing the maximum length (which may, as indicated in the previous paragraph, require you to scan the arguments that match "%s"s), and proceeding from there.