LWN.net Logo

snprintf() not the only way

snprintf() not the only way

Posted Feb 5, 2004 3:35 UTC (Thu) by Ross (subscriber, #4065)
Parent article: snprintf() confusion

Another approach is to calculate the maximum length of the resulting
string. This may be difficult if there are strings or variable formats.
If there are strings you can use the precision specifier to limit the
length of those strings. If it is not possible to staticly determine the
maximum length or it is too large to allocate every time you can do
dynamic determination of the length by testing the lengths of the strings
or of the dynamic formats.


(Log in to post comments)

snprintf() not the only way

Posted Feb 5, 2004 21:18 UTC (Thu) by iabervon (subscriber, #722) [Link]

To calculate the right buffer size, you should use code which stays tied
to the format and conversion code. Like, for example, "snprintf(NULL, 0,
format, ...)"; the kernel version of vsnprintf actually obeys a zero size
and doesn't dereference the buffer. It would actually be a neat trick to
detect this case and handle it, if possible, at compile time. That way,
people could get the compiler to size their buffers correctly
automatically.

snprintf() not the only way

Posted Feb 7, 2004 10:07 UTC (Sat) by ThePythonicCow (subscriber, #11308) [Link]

Utterly impossible to size at compile time -- the length of what is added to the buffer varies with runtime data. Something as simple as snprintf(buf, 999, "%d", random()); could put 1 to 10 digits in buf.

Copyright © 2008, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds