vsprintf considered dangerous

Mark Bromley bromley at think.COM
Mon Apr 4 15:41:09 AEST 1988


In article <1219 at ucsfcca.ucsf.edu> roland at 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



More information about the Comp.lang.c mailing list