Julian said:
'evening.
I'm not new to C and have been programming in it since I was 8 but
here's a strange problem I've never seen before.
When I compile a program from our C course with a windows compiler
there is no problem but when I try to compile it with a linux compiler
it complains that
a_03.c:(.text+0 x4d): warning: the `gets' function is dangerous
and should not be used.
Is linux more dangerous than windows?
No. Your Linux compiler warned you about a dangerous function that should
never be used. Your Windows compiler clearly forgot to do this. So it
could be argued that Windows is more dangerous than Linux.
Where can I download a
non dangerous gets function?
Nowhere. 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.
Instead, you can use fgets(), another standard ISO C function, which lets
you specify the size of the buffer, and which will not attempt to store
more in the buffer than you say will fit. So if you get the size right,
fgets() is not dangerous.
I have never used gets before is
there undefined behavior somewhere?
It depends on how well-behaved your user is (will they restrain themselves
and only type as many characters as you've provided for in your buffer?),
but it's safest to assume that you should never, ever, ever use gets().
Here is a trimmed down example program from my assignment that
demonstrates the problem
#include <stdio.h>
#include <malloc.h>
C has no header by that name (although some implementations do). For the
prototypes for malloc and free, #include <stdlib.hinstea d.
>
void main()
int main(void)
{
char *string;
printf("enter string (max 2000 chars): ");
fflush(stdin);
The behaviour of fflush is defined only for streams open for output or
update, whereas stdin is open only for input. In short, Don't Do That.
fflush(stdout);
That's fine, and meaningful in this case, because your printf string didn't
end in a newline, so you need to flush data from the buffer to the output
device.
string = (char *)malloc(2001);
string = malloc(2001); will be perfectly adequate. You do not need the
cast, and in fact it's a bad idea.
if(!string) exit(1);
Better: exit(EXIT_FAILU RE); This macro is defined in <stdlib.hand has
portable semantics.
gets(string);
No, use this instead:
if(fgets(string , 2001, stdin) != NULL)
{
printf("you entered: %s\n", string);
free(string);
}
exit(0);
}
On windows with TurboC and Lcc no error is printed. On linux with
gcc it says gets is dangerous.
Please advise my instructor says gcc is overly pedantic.
Your instructor is underly pedantic. (So is gcc, unless you kick it hard.)
--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999