Re: sscanf() safety
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
> http://code.google.com/p/ertf . I tried kcachegrind on my binaries and found
> that getc() is taking a lot of time. Obviously, character read from files is
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.
|All times are GMT. The time now is 09:43 PM.|
Powered by vBulletin®. Copyright ©2000 - 2013, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.