c : gets() and fputs() are dangerous functions?

4.5k views Asked by At

In the computer lab at school we wrote a program using fputs and the compiler returned an error gets is a dangerous function to use and a similar error for fputs

but at home when i type in this bit of code:

#include <stdio.h>
main()
{
    FILE *fp;
    char name[20];
    fp = fopen("name.txt","w");
    gets(name);

    fputs(name,fp);
    fclose(fp);
}

i get no errors what so ever. The one at school was similar to this one, just a bit lengthy and having more variables.
I use codeblocks at home and the default gcc provided with fedora at school.
Could it be a problem with the compiler?

5

There are 5 answers

0
paxdiablo On

gets is certainly dangerous since there's no way to prevent buffer overflow.

For example, if your user entered 150 characters, that would almost certainly cause problems for your program. Use of scanf with an unbounded "%s" format specifier should also be avoided for input you have no control over.

However, the use of gets should not be an error since it complies with the standard. At most, it should be a warning (unless you, as the developer, configures something like "treat warnings as errors").

fputs is fine, not dangerous at all.

See here for a robust user input function, using fgets, which can be used to prevent buffer overflow.

0
Alok Save On

With gets you need exactly know how many characters you will read and accordingly use a large enough buffer. If you use a buffer which is lesser than the contents of the file you read, you end up writing beyond the bounds of your allocated buffer and this results in an Undefined Behavior and an Invalid program.

Instead you should use fgets which allows you to specify how much data to read.

You don't get any errors because most likely your allocated buffer name is big enough to hold the contents of you file name.txt but if it was not then its a problem and hence the compiler issues the warning.

0
Sean Dawson On

It would just be the different settings of the different compilers. Maybe the compiler that Codeblocks uses isn't as verbose or has warnings turned off.

Regardless of the compiler they are dangerous functions to use as they have no checks for buffer overflow. Use fgets or fputs instead.

0
Shamim Hafiz - MSFT On

As for problems, there isn't any problem with any of the compilers. If you look at the link provided by Timothy Jones, you would understand why this warning is issued. As for different versions of compiler, compilers are configured differently to issue different levels of warning.

0
Steve Summit On

The other answers have all addressed gets, which is really and truly dangerous.

But the question also mentioned fputs. The fputs function is perfectly safe; it does not have these kinds of security concerns.

I believe the OP was probably mistaken in suggesting that the compiler had warned about fputs.