I want to know the disadvantages of scanf()
.
In many sites, I have read that using scanf
might cause buffer overflows. What is the reason for this? Are there any other drawbacks with scanf
?
I want to know the disadvantages of scanf()
.
In many sites, I have read that using scanf
might cause buffer overflows. What is the reason for this? Are there any other drawbacks with scanf
?
Problems I have with the
*scanf()
family:printf()
, you can't make it an argument in thescanf()
call; it must be hardcoded in the conversion specifier.scanf("%d", &value);
will successfully convert and assign 12 tovalue
, leaving the "w4" stuck in the input stream to foul up a future read. Ideally the entire input string should be rejected, butscanf()
doesn't give you an easy mechanism to do that.If you know your input is always going to be well-formed with fixed-length strings and numerical values that don't flirt with overflow, then
scanf()
is a great tool. If you're dealing with interactive input or input that isn't guaranteed to be well-formed, then use something else.Yes, you are right. There is a major security flaw in
scanf
family(scanf
,sscanf
,fscanf
..etc) esp when reading a string, because they don't take the length of the buffer (into which they are reading) into account.Example:
clearly the the buffer
buf
can hold MAX3
char. But thesscanf
will try to put"abcdef"
into it causing buffer overflow.The problems with scanf are (at a minimum):
%s
to get a string from the user, which leads to the possibility that the string may be longer than your buffer, causing overflow.I very much prefer using
fgets
to read whole lines in so that you can limit the amount of data read. If you've got a 1K buffer, and you read a line into it withfgets
you can tell if the line was too long by the fact there's no terminating newline character (last line of a file without a newline notwithstanding).Then you can complain to the user, or allocate more space for the rest of the line (continuously if necessary until you have enough space). In either case, there's no risk of buffer overflow.
Once you've read the line in, you know that you're positioned at the next line so there's no problem there. You can then
sscanf
your string to your heart's content without having to save and restore the file pointer for re-reading.Here's a snippet of code which I frequently use to ensure no buffer overflow when asking the user for information.
It could be easily adjusted to use a file other than standard input if necessary and you could also have it allocate its own buffer (and keep increasing it until it's big enough) before giving that back to the caller (although the caller would then be responsible for freeing it, of course).
And, a test driver for it:
Finally, a test run to show it in action: