K
Keith Thompson
jaysome said:The function gets() does not have an input size. But that didn't stop
the authors of the C standard from defining gets() to return a
pointer. If the return value is NULL, a read error occurred, and the
array contents are indeterminate. This implies that you must always
check the return value of gets(), if you want to avoid accessing an
array contents that is indeterminate.
Yes, but checking the return value of gets() is not sufficient. If
gets() overflows its buffer, it's likely to do so silently, returning
a valid pointer to indicate success but giving no indication that it's
just clobbered some critical data. Applying strlen() to the result
might tell you that an overflow occurred, but by then it's far too
late.
Checking the return value of gets() is like checking your fuel gauge
after your car has crashed. It *might* tell you something useful, but
you have to consider the possibility that the gauge itself was damaged
in the crash. (In a more apt analogy, you wouldn't be sure whether
the car has crashed or not.)
You can and should avoid the pitfalls of gets() (accessing an array
contents that is indeterminate, and undefined behavior), by not using
gets().
Indeed.