Re: Why is it dangerous?
- From: Antoninus Twink <nospam@xxxxxxxxxxxxxx>
- Date: Sun, 10 Aug 2008 11:25:38 +0000 (UTC)
On 10 Aug 2008 at 0:59, Richard Heathfield wrote:
Julian said:
a_03.c:(.text+0x4d): warning: the `gets' function is dangerous
and should not be used.
The functionality of gets() is defined by ISO; it takes a pointer to
the first character in a buffer, and stores an entire line from stdin
into that buffer, *regardless of the buffer's size*!! There is no safe
way to use such a function.
Of course, this is nonsense. There is a perfectly safe way to use
gets(), namely by being in control of what appears on stdin. Here in the
real world, people write all sorts of scraps of in-house code to run
once and forget about. They use fscanf() without elaborate error
checking, because they are 100% sure of the format of the input files.
gets() is no different.
Of course, in any production code, or any code at all where someone
other than the programmers will be able to decide what appears on stdin,
then gets() should not be used, the return value of p=malloc(10) should
be checked, etc. etc.
Instead of gets(), use whatever safe function is available on your
platform. For example, on GNU systems there is a getline() function
provided by stdio.h, which will dynamically allocated a big enough
buffer using malloc(). Or, roll your own getline function if portability
is a big issue for you.
.
- Follow-Ups:
- Re: Why is it dangerous?
- From: James Dow Allen
- Re: Why is it dangerous?
- References:
- Why is it dangerous?
- From: Julian
- Re: Why is it dangerous?
- From: Richard Heathfield
- Why is it dangerous?
- Prev by Date: Re: Variable naming conventions.
- Next by Date: Re: Dynamic allocation of multi dimensional array
- Previous by thread: Re: Why is it dangerous?
- Next by thread: Re: Why is it dangerous?
- Index(es):
Relevant Pages
|