Basic and Advance C Question:
Download Job Interview Questions and Answers PDF
Why does everyone say not to use gets?
Answer:
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. (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, 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.for a code fragment illustrating the replacement of gets() with 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.for a code fragment illustrating the replacement of gets() with fgets().
Download C Programming Interview Questions And Answers
PDF
Previous Question | Next Question |
If fflush wont work, what can I use to flush input? | What is the deal on sprintfs return value? |