Path: utzoo!mnetor!uunet!husc6!mailrus!ames!think!bromley From: bromley@think.COM (Mark Bromley) Newsgroups: comp.lang.c Subject: Re: vsprintf considered dangerous Message-ID: <18746@think.UUCP> Date: 4 Apr 88 05:41:09 GMT References: <36@lotus.UUCP> <1219@ucsfcca.ucsf.edu> Sender: usenet@think.UUCP Reply-To: bromley@lysippe.think.com.UUCP (Mark Bromley) Organization: Thinking Machines Corporation, Cambridge, MA Lines: 29 In article <1219@ucsfcca.ucsf.edu> roland@rtsg.lbl.gov (Roland McGrath) writes: >The GNU C library has such a function. It's called "vsnprintf" and it >takes a maximum-length argument (there's also an "snprintf"). >When I finish the GNU C library it will be freely distributed and you >can then use it. > >In general, one should take care when using the sprintf functions. >Make sure you know the maximum length that the format specification >will produce and arrange to have at least that much space allocated. >-- I have always disliked the sprintf and sscanf interface. A somewhat different interface would allow the standard functions to be used with complete error checking in the case of io to/from strings. In the context of stdio, what would be provided is an sopen function, which is given a buffer and its size and returns a stream in which i/o is done directly to the buffer. Since the size is given at open time, attempts to write outside the buffer can be trapped. Implementing this on top of stdio should be almost trivial. In fact, every implementation of sprintf/sscanf that I have seen uses a mechanism almost identical to this internally. This method for dealing with i/o to strings is of course not original. Common Lisp provides the functions make-string-input-stream and make-string-output-stream. C++ provides essentially this functionality with a somewhat cleaner syntax. Mark Bromley