LWN.net Logo

snprintf() confusion

snprintf() confusion

Posted Feb 5, 2004 8:32 UTC (Thu) by ThePythonicCow (subscriber, #11308)
Parent article: snprintf() confusion

Pre-calculating the length of the resulting string, as suggested
above, doesn't cut it.

(1) It requires adding error prone code to pre-walk the result,
duplicating the choice of what to print. Soon the pre-walk
code and the actual format will get out of sync again.
(2) Sometimes you are printing variable stuff, that is changing as
you print it (on a multiprocessor). So you don't know the
length until you know it.
(3) Sometimes you are printing several items into a buffer, while
walking a list or something. You can't afford to walk the list
twice, and besides - see (2) above.
(4) The idea of a buffer limited routine like snprintf is to help
the user avoid disastrous mistakes that only blow up rarely.
Given all the difficulties (listed above) in getting the 'right'
answer as to the resulting length, you _still_ need a buffer
limited routine, because you still risk running off the end.


(Log in to post comments)

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