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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With