LWN.net Logo

snprintf() confusion

snprintf() confusion

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

The biggest problem that this snprintf patch will fix is not noted in the article above.

There were a couple hundred places in the kernel that would loop:

    len += snprintf (buf+len, buflen-len, "...", ...);
accumulating the number of non-nul chars written into a buffer in 'len'. Well, actually, unbeknownst to the coder, accumulating the total number of characters that could have been written, if the buffer were big enough.

The 2nd snprintf parameter (buflen-len, here) would go negative, when the total number of chars that could have been written into the buffer exceeded the buffer length.

Since this 2nd parameter is passed as a type size_t (unsigned), this meant that the next call to snprintf claimed that the available buffer size was **huge**. A license to overrun buffers. Not something you desire in your average kernel.

The patch going in will have any buffer size that is huge (high bit set) be special cased as if it was zero, putting nothing more in the buffer.


(Log in to post comments)

snprintf() confusion

Posted Feb 5, 2004 16:33 UTC (Thu) by hazelsct (guest, #3659) [Link]

Hmm, seems like a better approach might be to track down such uses of snprintf() and replace them with something like:
if ((len += snprintf (buf+len, buflen-len, "...", ...)) > buflen) {
        optionally deal with the error;
        len = buflen;
}
The branch shouldn't cost more than the call to snprintf (unless it's inlined and extremely efficient), and you get to deal with error conditions, making it better than the old snprintf behavior.

Of course, this takes time (janitors?), but aside from that, I'm not sure I see why this snprintf behavior is a problem...

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