Malcolm said:
Chris Torek said:
But observable, repeatable, predictable incorrect behavior.
Moreover, programs that use gets() in this same way also
silently truncate input:
gets(buf); /* XXX bad */
error = FALSE;
...
Since the "error" variable happens to alias &buf[sizeof buf], this
truncates the input, silently. In other words, the function you
claim to be "superior" has the same flaw as fgets(), plus additional
flaws.
If you're unlucky.
Undefined behaviour is always incorrect behaviour _by the program_, but
usually correct behaviour _by the computer_.
Depends on what you mean by "correct", I suppose.
fgets() can be used safely if you know what you're doing. With proper
use, it cannot cause a buffer overflow, and you can always tell
whether the input line was truncated by checking the last character of
the input string. It's not ideal; the non-standard but portably
implemented ggets()is arguably better, at least in some ways. If you
aren't able to use fgets() safely, you probably shouldn't be
programming in C (or in any other language).
(That last isn't directed at you personally. I presume you are
competent enough to avoid the pitfalls of fgets(). I'm atacking your
arguments, not your competence.)
getc() can be used safely if you know what you're doing. Integer
addition can be used safely if you know what you're doing. And so on,
for nearly every feature of the language.
gets() cannot be used safely. Undefined behavior is not safe. A
program that potentially trampling on other variables is not safe.
Living with possible crashes rather than learning how to use the
language properly is, frankly, not the mark of a competent programmer.
In this case, if the buffer overflow is only two or three bytes, then the
input will be silently truncated. However the chances are that sooner or
later someone will enter a longer input, and the error will be very noisily
flagged, probaly with a message like "segmentation fault". This is what you
want to happen, given that it is incorrect, it should produce no results.
Just write correct code in the first place. Code that uses gets() is
not, and cannot be, correct code. Yes, it's possible to write
incorrect code using fgets(). It's also possible (though perhaps
slightly inconvenient) to write correct code using fgets(). It's also
possible to write correct or incorrect code using ggets(), or getc(),
or nearly anything else.
[snip]
By replacing undefined behaviour with wrong but defined behaviour, you are
reducing the number of type 1 and type 2 errors, at the cost of more type 3
and type 4 errors. That's why Martin's advice was so badly wrong
Nobody has advocated replacing undefined behavior with wrong but
defined behavior. The trick is to replace undefined behavior with
correct and defined behavior. Nothing else is acceptable. Suggesting
otherwise makes it difficult to take you seriously.
Once again, yes, fgets() has problems. It's simply foolish to think
that gets() could be the solution.