prev up next   top/contents search

comp.lang.c FAQ list · Question 12.23

Q: Why does everyone say not to use gets()?


A: Unlike fgets(), gets() cannot be told the size of the buffer it's to read into, so it cannot be prevented from overflowing that buffer if an input line is longer than expected--and Murphy's Law says that, sooner or later, a larger-than-expected input line will occur. [footnote] (It's possible to convince yourself that, for some reason or another, input lines longer than some maximum are impossible, but it's also possible to be mistaken, [footnote] and in any case it's just as easy to use fgets.)

The Standard fgets function is a vast improvement over gets(), although it's not perfect, either. (If long lines are a real possibility, their proper handling must be carefully considered.)

One other difference between fgets() and gets() is that fgets() retains the '\n', but it is straightforward to strip it out. See question 7.1 for a code fragment illustrating the replacement of gets() with fgets().

References: Rationale Sec. 4.9.7.2
H&S Sec. 15.7 p. 356


prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North