Out of fgets() and gets() which function is safe to use and why?

1 reply [Last post]
dhanunjaya
Offline
Last seen: 9 years 33 weeks ago
Joined: 2009-04-26
bOt Points: 153

anish
Offline
Last seen: 10 years 17 weeks ago
Joined: 2009-04-08
bOt Points: 94
gets is an insecure function,

gets is an insecure function, its careless use can lead to errors. If you want to use gets, consider using fgets instead, supplying stdin as the file reference parameter.

The parameter given to gets must be an already allocated array of characters, not an
uninitialised char * pointer; gets will never allocate memory.

The array given to gets must be big enough to hold any line that could conceivably be
input. C++ and C are incapable of telling how long an array is. If it is not long enough
for the data that is read, other data (and perhaps program code) will be overwritten.
Thus gets is not a safe function for use in critical applications.

gets does NOT check the size of the buffer and overflow on the stack can occour. Because of this you should use fgets in preferance.