On Jun 27, 9:54 pm, Kushal Kumaran <kushal.kumaran+pyt...@gmail.com> wrote: > On Mon, Jun 28, 2010 at 2:00 AM, Jorgen Grahn <grahn+n...@snipabacken.se> > wrote: > > On Sun, 2010-06-27, Lawrence D'Oliveiro wrote: > >> In message <roy-854954.20435125062...@news.panix.com>, Roy Smith wrote: > > >>> I recently fixed a bug in some production code. The programmer was > >>> careful to use snprintf() to avoid buffer overflows. The only problem > >>> is, he wrote something along the lines of: > > >>> snprintf(buf, strlen(foo), foo); > > >> A long while ago I came up with this macro: > > >> #define Descr(v) &v, sizeof v > > >> making the correct version of the above become > > >> snprintf(Descr(buf), foo); > > > This is off-topic, but I believe snprintf() in C can *never* safely be > > the only thing you do to the buffer: you also have to NUL-terminate it > > manually in some corner cases. See the documentation. > > snprintf goes to great lengths to be safe, in fact. You might be > thinking of strncpy.
Indeed, strncpy does not copy that final NUL if it's at or beyond the nth element. Probably the most mind-bogglingly stupid thing about the standard C library, which has lots of mind-boggling stupidity. Whenever I do an audit of someone's C code the first thing I do is search for strncpy and see if they set the nth character to 0. (They usually didn't.) Carl Banks -- http://mail.python.org/mailman/listinfo/python-list