473,803 Members | 3,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why the usage of gets() is dangerous.

Hi all,

Whenever I use the gets() function, the gnu c compiler gives a
warning that it is dangerous to use gets(). why...?

regards,
jayapal.
Nov 16 '07
104 5283

CJ <no****@nospam. comwrote in message
news:sl******** ***********@nos pam.com...
On 16 Nov 2007 at 20:47, ja*********@ver izon.net wrote:

It's trivial to replace any call to gets() with a similar call to
fgets() with minor modifications to the surrounding code, and that
change is sufficient to completely avoid the buffer overruns. I don't
know of any legitimate reason for not doing so.

It's much more typing!
Leading to increased carpal tunnel syndrome!

Here's how to avoid some of the typing:

#define GET_INPUT_STRIN G(string_array) \
get_input_strin g(string_array, sizeof(string_a rray))

char *get_input_stri ng(char *string_array,i nt array_size) {
int string_size;

GetInput :

fgets(string_ar ray,array_size, stdin);

string_size=str len(string_arra y);

if(string_array[string_size-1]!='\n') {
fflush(stdin); /* NOT PORTABLE!!! */
printf
("\nCAUTION: input too long, should be less than %d characters",
array_size);
printf("\nTry again: ");
goto GetInput;
}

else string_array[string_size-1]='\0';

return string_array;
}

Stick that in a little library that you link into all the programs that
require getting standard input (along with some automatic menu
generation routines, etc.), and if GET_INPUT_STRIN G is too much
typing you can just call it GIS() or something. The only problems
are: 1) you could wind up in an endless user idiocy loop, but it
beats crashing your program when the same idiot types too much
stuff into gets(), and 2) the fflush(stdin) works for my compiler but
of course is not guaranteed for yours...

---
William Ernest Reid

Nov 17 '07 #31
"Harald van Dijk" <tr*****@gmail. comwrote in message
>
>It is illegal
to convert from a struct S * to a char *,

It's allowed for two reasons here. Firstly, *any* object can be addressed
as an array of char. Given int i, ((char *) &i) through (char *) &i +
sizeof i are all valid pointers. Given struct S s, (char *) &s + sizeof s
are all valid pointers. The second reason you mention below.
I nodded. Yes, it is illegal to convert from type x * to type y *, except

when x or y is void.
when y is unsigned char - char yes and no, you may trap when you dereference
the pointer.
when y is the first member of a struct of type x.
when y is a struct of which x is the first member.
>
[ problem is ]
struct S s[2];
char *ptr = &s1.firstmember ;
struct S *ptr2 = (struct S *) ptr;
ptr2--;
>
It has to be able to construct data that is no longer available.
I think you have managed to defeat it using the last rule. We can give the
ptr2 the bounds of s[1], not easily but not with too many problems. However
it is virtually impossible to give it the bounds of s. You'd have to store a
fourth pointer with every pointer giving the "mother" object. It becomes
totally unwieldy.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Nov 17 '07 #32
Malcolm McLean wrote, On 16/11/07 23:19:
>
"Richard Heathfield" <rj*@see.sig.in validwrote in message
>>It is possible,
though rather difficult, to implement a safe gets(), that is to say one
that always terminates the program with an error message if the
buffer is
exceeded.

Show me.
We'll declare that pointer cosist of three values - the address, the
start of the object, and the end of the object.
Now in the write to array code we specify that if the address execceds
the end of the object, the program is to terminate with an error meaage.

With this device we have a perfectly safe gets() fucntion. It cannot
return an incorrect string, or corrupt another variable, or put little
elves on screen. It can only fill the buffer correctly or report that it
has been exceeded.
However, unless you manage to get all hosted C implementations changed
to use this it is *still* not safe to call gets because your code might
be ported to an implementation that does not do this.
>>What is not possible to is implement is a safe fgets(), that is to say,
one that can be used safely given the limitations of the average human
programmer.

The fgets function is very easy to use safely.
Time after time it has been shown that this is not the case. Very often
people treat incomplete reads as full lines. So if the line contains a
drug dose your fgets() - enabled machine might deliver only one tenth of
the amount needed, given an off by one line length error.
As pointed out the last time you raised this example:
1) It would get spotted in a properly performed code review
2) It would get caught by properly done testing

So it would not hit production like that. Input validation is one of the
basics of safety-critical programming, it is even one of the basics in
writing SW for non-critical test equipment!

In any case, that people can use a function incorrectly does not mean it
cannot be used correctly easily.

Now let us take your use of gets with an implementation guaranteed to
abort the program in to a similar situation...

The drug dispenser reads a file on a regular basis to check what it
should be dispensing. At 3AM it come across an over-length line and the
program abort. The patient then does not get the drugs keeping him/her
alive and dies.

So by using a "safe" gets you have just made it impossible to safely
handle out-of-range input whereas it is easy to do with fgets.
--
Flash Gordon
Nov 17 '07 #33
jayapal wrote:
>
Whenever I use the gets() function, the gnu c compiler gives a
warning that it is dangerous to use gets(). why...?
Because it cannot be used safely. There is no length control. Two
possible replacements for it are fgets() (a C standard function)
and ggets() (a non-standard function). ggets is available in
source form, with no restrictions, as ggets.zip at:

<http://cbfalconer.home .att.net/download/>

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 17 '07 #34
Malcolm McLean wrote:
>
.... snip ...
>
Undefined behaviour means "undefined by the standard". It is
possible, though rather difficult, to implement a safe gets(),
that is to say one that always terminates the program with an
error message if the buffer is exceeded.
Consider yourself challenged to post the appropriate code, in
standard C.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 17 '07 #35
Malcolm McLean wrote:
"Richard Heathfield" <rj*@see.sig.in validwrote:
>>It is possible, though rather difficult, to implement a safe
gets(), that is to say one that always terminates the program
with an error message if the buffer is exceeded.

Show me.

We'll declare that pointer cosist of three values - the address,
the start of the object, and the end of the object. Now in the
write to array code we specify that if the address execceds the
end of the object, the program is to terminate with an error
meaage.
No good. Pointers do not necessarily contain those components.
You have to make it safe within the guarantees provided by the C
standard.

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home .att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Nov 17 '07 #36
On Fri, 16 Nov 2007 19:56:39 -0500, CBFalconer wrote:
Malcolm McLean wrote:
>>
... snip ...
>>
Undefined behaviour means "undefined by the standard". It is possible,
though rather difficult, to implement a safe gets(), that is to say one
that always terminates the program with an error message if the buffer
is exceeded.

Consider yourself challenged to post the appropriate code, in standard
C.
gets is a standard library function. Standard library functions need not
be written in standard C, and may make use of highly implementation-
specific features.

If you disagree, please give even just a single example of an
implementation of fopen or longjmp written purely in standard C.
Nov 17 '07 #37
CBFalconer wrote:
Malcolm McLean wrote:
>"Richard Heathfield" <rj*@see.sig.in validwrote:
>>>It is possible, though rather difficult, to implement a safe
gets(), that is to say one that always terminates the program
with an error message if the buffer is exceeded.
Show me.
We'll declare that pointer cosist of three values - the address,
the start of the object, and the end of the object. Now in the
write to array code we specify that if the address execceds the
end of the object, the program is to terminate with an error
meaage.

No good. Pointers do not necessarily contain those components.
You have to make it safe within the guarantees provided by the C
standard.
No, he doesn't. You're asking for more than Malcolm claimed.

Malcolm didn't claim that it could be made safe within the gaurantees
provided by the C standard. His claim is a much more modest one,
that it's possible for a (hypothetical) C implementation to provide a
"safe" gets() function, and I believe he's correct.

His solution requires the use of "fat pointers", which are not
widely implemented but are reasonably well understood. In such an
implementation, the char* parameter to gets() provides information
about the size of the buffer to which it points. (Portable C code
cannot make use of this information, but gets() needn't be implemented
in portable C.) If the size of the input line exceeds the size of the
buffer, the behavior is undefined. This means the implementation is
free to do whatever it likes, including terminating the program with
an error message (or discarding the remainder of the line, or leaving
the remainder of the line on the input stream).

I know of no C implementations that actually use fat pointers; even if
there were, the possibility of making gets() safe in one implementation
does no good for code that is to be used with other implementations .

I believe Malcolm's claim as stated is correct. It's not particularly
useful, but he didn't claim that it was; I believe it was merely an
intellectual excercise, not a serious proposal.
--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 17 '07 #38
Harald van Dijk writes:
>Sat, 17 Nov 2007 00:28:43 +0000, Malcolm McLean wrote:
>>>We'll declare that pointer cosist of three values - the address, the
start of the object, and the end of the object.
(..)
struct S {
char c[10];
int i;
} s;
(...)
A pointer to s.c would have to store the end as &s.c[10].

Okay, so then you can't get back the original &s?
If I remember correctly, (struct S *)s.c is indeed undefined. Or it
is defined but ((struct S *)s.c)->i and (struct S *)s.c + 1 are not.
Probably for similar reasons that the 'struct hack' is undefined.

--
Regards,
Hallvard
Nov 17 '07 #39
On Sat, 17 Nov 2007 23:21:19 +0100, Hallvard B Furuseth wrote:
Harald van Dijk writes:
>>Sat, 17 Nov 2007 00:28:43 +0000, Malcolm McLean wrote:
>>>>We'll declare that pointer cosist of three values - the address, the
start of the object, and the end of the object.
(..)
struct S {
char c[10];
int i;
} s;
(...)
A pointer to s.c would have to store the end as &s.c[10].

Okay, so then you can't get back the original &s?

If I remember correctly, (struct S *)s.c is indeed undefined. Or it is
defined but ((struct S *)s.c)->i and (struct S *)s.c + 1 are not.
Probably for similar reasons that the 'struct hack' is undefined.
Quoting from 6.7.2.1p13:
"A pointer to a structure object, suitably converted, points to its
initial member (or if that member is a bit-field, then to the unit in
which it resides), and vice versa."

The "and vice versa" means that a pointer to the initial member of a
structure can be converted back to a pointer to that structure object,
does it not? Technically, the initial member of the structure is an array
of char, not a char, but I believe I addressed that in my previous
message.
Nov 17 '07 #40

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

48
2743
by: Michael Sig Birkmose | last post by:
Hi everyone! Does anyone know, if it is possible to meassure the maximum stack usage of a C program throughout it's entire execution? -- Michael Birkmose
302
18623
by: Lee | last post by:
Hi Whenever I use the gets() function, the gnu c compiler gives a warning that it is dangerous to use gets(). Is this due to the possibility of array overflow? Is it correct that the program flow can be altered by giving some specific calculated inputs to gets()? How could anyone do so once the executable binary have been generated? I have heard many of the security problems and other bugs are due to array overflows.
89
6087
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be used." Could anybody tell me why gets() function is dangerous?? Thank you very much. Cuthbert
0
9700
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10292
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10068
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9121
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7603
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.