Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is gets() more dangerous than scanf()?

Tags:

c

It seems to me that both have the potential to overflow the buffer. Yet I'm adviced to never use gets() but still encouraged to use scanf().

Is it just because of the formatting arguments allowed in scanf() or is there any other reason?

like image 206
Dagoth Ulen Avatar asked Mar 13 '13 16:03

Dagoth Ulen


2 Answers

The gets function is not protected against buffer overflows.

With the scanf format string you can define the maximal length of the string to read from standard input and store in the given memory buffer. For example with scanf("%10s\n", str); a maximum of 10 characters will be read. The str buffer should be of 11 bytes to store the NULL terminating character.

Performance wise, if you only use scanf to workaround the buffer overflow issues of gets, prefer using the fgets function instead.

like image 172
greydet Avatar answered Oct 03 '22 15:10

greydet


Because you can input more characters than size of the buffer and gets() will happily allow it. Moreover, gets() has been deprecated (in C11). So the comparison with scanf() is no longer valid. Besides scanf() has its own problems when dealing with unformatted data.

So a better option would be fgets() and then process it as per your needs.

like image 31
P.P Avatar answered Oct 03 '22 16:10

P.P