Mabden wrote:
> "Dave Vandervies" <> wrote in message
> news:cjuojk$5r8$...
>
>>In article < >,
>>Sathyaish <> wrote:
>>
>>>I noticed that gets() reads into the buffer even if the you've not
>>>allocated enough memory. For instance, if you do:
>>
>>[snip]
>>
>>
>>>Please shed some light on this function's behaviour as regards buffer
>>>allocation.
>>
>>There's no way to avoid overwriting memory if the input is longer than
>>you expect. This means that it's impossible to use gets without
>
> creating
>
>>a bug that allows a buffer overrun.
>>The solution is to Don't Do That. Use something like
>> fgets(buf,sizeof buf,stdin)
>>instead if longer-than-expected input is an error (if the string you
>>get back doesn't include a '\n', either you have an input error or the
>>buffer is full and the rest of the line is still waiting in the
>
> input),
>
>>or google for ggets in posts here if input needs to be arbitrarily
>
> sized.
>
>
> I don't really see the need for a gets() or fgets(). It's just a loop to
> do getc() for you, so why not just do it yourself and _know_ what is
> going on. I'm generally looking for more than just the newline char when
> I'm parsing data so I just read a char at a time. I mean, aren't you
> going to go through the string (or line) you just inputted anyway?
> What's the point of parsing it twice?
Convenience. getc() gives you only one character of
look-ahead (because you can have only one ungetc()'d char
outstanding), so if you need more you'll need to manage
some kind of buffer anyhow.
Convenience. Once you've found a sequence of interesting
input characters you may want to do something with them, and
many of the "somethings" involve calling C library functions
like strcmp() or strtod() or even sscanf(), all of which
need to see the entire string at once.
Convenience is certainly not the be-all and end-all of
programming, but there's much to be said for it. Who among
us has not used the convenient printf(...) instead of the
equivalent but clumsier fprintf(stdout,...)? Who has not
used printf() when puts() would have done the job?
There are plenty of situations where character-by-character
input is preferable: You can handle Really Long Lines without
requiring Really Big Buffers, you can change your mind in
mid-stream before reading too far ahead (scanf() couldn't
be implemented atop fgets(), for example), and so on. But
in situations where these aren't of great concern, fgets()
is simply ... convenient.
(By the way, I'm not suggesting that fgets() is perfect.
Its return value is particularly annoying, as it tells you
something you already knew instead of something you didn't,
something that fgets() has figured out that you may need to
figure out all over again. fgets() is blemished -- but so
are we all, says my theology professor.)
--