mailing list archives
Re: better snprintf replacement, anyone?
From: mouse () RODENTS MONTREAL QC CA (der Mouse)
Date: Tue, 22 Jul 1997 10:19:54 -0400
Quite often I find people saying to me "Why do you use snprintf()
all over the place to avoid buffer overflows, and not try to use
other techniques. Using snprintf() makes it hard for us to port the
code to legacy systems."
My reaction to this is "not using punched cards makes it hard to port
to (other) legacy systems". The point beyond which a system is so
legacy it's not worth even trying to support it, for me, includes
systems without calls like snprintf.
It's still not clear to me why people only suggest snprintf(). I
would imagine that there are only a few cases were a program coulnd't
pre-determine the length of a string that would be generated by
sprintf() and malloc() enough memory to contain it all.
Probably, yes, since the whole *printf() family exists in
full-source-available forms, so any program can just haul in the whole
thing, it can figure out the total length.
Yes, it's a little extra work to strlen() all the variables you're
pulling in, but you ensure that you have a large enough buffer, you
eliminate the buffer overflow problem, and you don't truncate the
You also can't handle anything but strings that way (there's no a
priori way to tell how many characters something like %d can take up,
though admittedly (CHAR_BIT*sizeof(int)/3)+2 is a reasonable maximum),
and you're assuming whatever the result will be fed to can handle an
arbitrarily large string.
Is malloc()-ing the memory *that* inefficient? Less efficient than
the scanning and parsing snprintf() must do to the format string?
You're going to have to do the scanning and parsing _anyway_ in order
to do the "printing", so there's no call to compare that cost against
mouse () rodents montreal qc ca
7D C8 61 52 5D E7 2D 39 4E F1 31 3E E8 B3 27 4B
Re: better snprintf replacement, anyone? Bill Rugolsky Jr. (Jul 22)
Re: better snprintf replacement, anyone? der Mouse (Jul 22)
Re: better snprintf replacement, anyone? Sten Gunterberg (Jul 22)
Re: better snprintf replacement, anyone? Peter Jeremy (Jul 22)
Re: better snprintf replacement, anyone? der Mouse (Jul 23)
- Re: better snprintf replacement, anyone?, (continued)