Re: better snprintf replacement, anyone?

James Bonfield (jkb@MRC-LMB.CAM.AC.UK)
Tue, 22 Jul 1997 12:11:24 +0100

On 22nd July, Steve Coile wrote:

>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 string.

You have to be careful with this. Remember that a %.*s sprintf can use any
amount of buffer, depending on the size argument. Summing strlen's isn't
enough. I wrote a worst-cast scenario function to determine the maximum length
of output for a sprintf style request. It doesn't handle unicode or anything
fancy, but does handle most things reasonably well. I'm not saying it's 100%
foolproof (eg it makes assumptions that we're not on anything bigger than a
64bit system), but it's a start.

The idea is that you can use something like
l = flen("%*.*e %*c\n", 10, 5, 9.0, 20, 'x')
to compute a maximum bounds for 'l', to then either malloc or do error
reporting when using fixed sized buffers. I should add that I originally wrote
this for use in a non security oriented environment, but it strikes me as a
handy alternative to snprintf, which always struck me as an "error checking
too late" approach.

For the code, see the following two files:

ftp://ftp.mrc-lmb.cam.ac.uk/pub/jkb/vlen.c
ftp://ftp.mrc-lmb.cam.ac.uk/pub/jkb/vlen.h

Comments and bug reports are most welcome.

James

--
James Bonfield (jkb@mrc-lmb.cam.ac.uk)   Tel: 01223 402499   Fax: 01223 213556
Medical Research Council - Laboratory of Molecular Biology,
Hills Road, Cambridge, CB2 2QH, England.
Also see Staden Package WWW site at http://www.mrc-lmb.cam.ac.uk/pubseq/