home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.os.linux
- Path: sparky!uunet!think.com!rpi!batcomputer!eos.acm.rpi.edu!kutcha
- From: kutcha@eos.acm.rpi.edu (Phillip Rzewski)
- Subject: Re: "the `gets' function is unreliable and should not be used"??!!!
- Message-ID: <1992Dec31.222242.16868@tc.cornell.edu>
- Sender: news@tc.cornell.edu
- Nntp-Posting-Host: eos.acm.rpi.edu
- Organization: The Voice of Fate
- References: <C058sJ.Fuu@news.cso.uiuc.edu>
- Date: Thu, 31 Dec 1992 22:22:42 GMT
- Lines: 53
-
- In article <C058sJ.Fuu@news.cso.uiuc.edu> dld54032@uxa.cso.uiuc.edu (Dave Dribin) writes:
- >I was trying to compile some programs that I had written for class on
- >a Sun Sparc and compile using gcc, and I kept getting this error that
- >the `gets' function is unreliable. How can it be unreliable! It won't
- >even work with this simple program:
- >#include <stdio.h>
- >
- >main() {
- > char str[256];
- >
- > gets(str);
- > puts(str);
- >
- > return(0);
- >}
- >
- >I am using SLS Linux v99.0. Did I install anything wrong, or is the function
- >really unreliable. I would think that all the standard ASNI functions would
- >be reliable! Thanx in andvance, and happy new year...
-
- Well, it's reliable in the sense that it does what you want it to (get a
- string) but it's unreliable in the sense that it can cause trouble. Basically
- the gcc message stems from the fact that gets() just reads the string into
- a memory location without any regard to how much can be fit there without
- causing memory violations. On the other hand, fgets() has a handy argument
- that lets you limit how many characters can be read. So as for your program,
- you probably would rather:
-
- #include <stdio.h>
-
- main() {
- char str[256];
-
- fgets(str, 256, stdin);
- puts(str);
-
- return(0);
- }
-
- With your original program, if I typed 1000 characters, it would probably
- casue a SEGV and dump core. With the version I just typed up here, it would
- just read the first 255 characters (it acutally reads n - 1, so there is room
- for a '\0') and continue happily.
-
- I happen to think the gcc error message is a tad annoying, but it's
- only trying to be helpful. I get the impression that once people saw the
- problems gets() could cause they'd try to stamp out its use forever by
- just reminding people over and over again why it is a bad thing. :)
-
- --
- Phillip Andrew Rzewski Internet: kutcha@acm.rpi.edu
- "Don't wait; while you're waiting, you're dying."
- --- Peter Hammill
-