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?
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.