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

烂漫一生 提交于 2019-12-04 21:26:12

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.

paxdiablo

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.

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.

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.

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!