ubaka
08-28-2002, 10:08 PM
why can't my gcc 2.95 compiler compile gets()? it gives error: the 'gets' is dangerous and should not be used.
how do i get round this?
how do i get round this?
|
Click to See Complete Forum and Search --> : gets() error! HELP! ubaka 08-28-2002, 10:08 PM why can't my gcc 2.95 compiler compile gets()? it gives error: the 'gets' is dangerous and should not be used. how do i get round this? Energon 08-28-2002, 11:16 PM Any reason you can't use fgets()? The compiler is doing you a very, very, very huge favor by not letting you use gets(). But if you really can't use fgets(), how are you compiling? What's the command line you use (or the make line that's being used)? X_console 08-28-2002, 11:38 PM It's not really an error, just a warning. If you try to run the executable it'll probably run. The reason gets() is dangerous is because it doesn't check for the length of input, whereas fgets does. For example: char input[10]; printf("Enter something: "); gets(input); printf("You entered %s\n", input); If you input something like aaaaaaaaaaaaaaaaaaaa you'll get a segmentation fault. On the other hand if you do: char input[10]; printf("Enter something: "); fgets(input, sizeof(input), stdin); printf("You entered %s\n", input); it doesn't matter how long the input is, because fgets() will only take in the first 10 characters and anything else is thrown away. ubaka 08-30-2002, 06:21 AM :D thanks alot guys TheLinuxDuck 09-05-2002, 05:44 PM ubaka: Also, I feel it important to point out that using sizeof(varName) to accept input as X_Console has pointed out will work great, but only for char-arrays that are given sizes upon definition. If the char in question is a pointer, this won't work, because a pointer is always going to be 4 bytes (unless someone knows something I don't). I don't recommend getting in the habit of doing it this way because it could inevitably introduce a bug that could easily be overlooked, especially if you are using both predefined sizes and allocated arrays, or pointers to other things. char *myInput; int mySize = 10; myInput = (char *)malloc(sizeof(char) * mySize); if(myInput == NULL) perror("Couldn't allocate memory"); else { printf("Enter something: "); fgets(myInput, mySize, stdin); printf("You entered %s\n", myInput); } Also, take a look at the last post in this thread: http://www.linuxnewbie.org/forum/showthread.php?s=&threadid=63044 It has to do with an *extra* characters not received by fgets. Unless X_Console knows something I don't, the extra chars are not thrown away, but left in the input buffer. The post at the end of that link will show you how to clean that up, so anything left over will be thrown away. Hope that helps! justlinux.com
Copyright Internet.com Inc. All Rights Reserved. |