Re: sscanf() safety

Discussion in 'C Programming' started by Nobody, Dec 23, 2010.

  1. Nobody

    Nobody Guest

    On Thu, 23 Dec 2010 23:20:54 +0530, Cross wrote:

    > I am working on an rtf renderer and parser. My code is hosted at
    > . I tried kcachegrind on my binaries and found
    > that getc() is taking a lot of time. Obviously, character read from files is
    > slow.

    FWIW, with GNU libc, you can replace getc() with getc_unlocked() if you
    aren't accessing the file from multiple threads. The main reason why
    getc() is so slow is that it has to lock the FILE structure for each
    operation. The _unlocked version is just:

    #define _IO_getc_unlocked(_fp) \
    (_IO_BE ((_fp)->_IO_read_ptr >= (_fp)->_IO_read_end, 0) \
    ? __uflow (_fp) : *(unsigned char *) (_fp)->_IO_read_ptr++)

    getc() itself used to be implemented this way before threading was
    available on Linux.

    Alternatively, you could just implement your own version of getc based
    upon the above.

    > So, I decided to read the whole file into memory as a char buffer.
    > Please feel free to comment and suggest on the following code. Now, I
    > want to scan the char buffer using sscanf(). However, I remember once I
    > heard in a chat room that sscanf() has buffer overflow vulnerabilities.
    > I would like pointers on this and would like to know how I can use
    > sscanf() safely.

    The "%s" and "%[...]" specifiers will read as many matching characters as
    are available. The buffer needs to be large enough to hold all of them. If
    you don't know how many characters might be read, the buffer needs to be
    able to hold the entire input.

    If you're reading an unknown amount of data into a fixed-size buffer,
    specify a maximum field width. E.g. "%15s" will read at most 15
    characters, plus a terminating NUL byte (which is written regardless of
    whether the field width was exceeded).

    If a field exceeds the maximum field width, it's likely that subsequent
    parsing will fail, but you won't get a buffer overflow. If you need to be
    able to read data containing unlimited-length fields, you'll need to
    choose a different approach.
    Nobody, Dec 23, 2010
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Anonymous
    Oct 30, 2003
  2. pramod
    Lew Pitcher
    Jan 6, 2004
  3. Mike

    sscanf and c++!

    Mike, Jun 8, 2004, in forum: C++
  4. Jens Thoms Toerring

    Re: sscanf() safety

    Jens Thoms Toerring, Dec 23, 2010, in forum: C Programming
    Jens Thoms Toerring
    Jan 10, 2011
  5. Barry Schwarz

    Re: sscanf() safety

    Barry Schwarz, Dec 24, 2010, in forum: C Programming
    Barry Schwarz
    Dec 24, 2010

Share This Page