Why is it usually a bad idea to use gets()? Suggest a workaround. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is it usually a bad idea to use gets()? Suggest a workaround.

gets() can potentially overflow the input buffer and start overwriting memory . Why❓

3rd Jan 2020, 10:56 AM
Gurpej Singh
Gurpej Singh - avatar
2 Answers
+ 2
Answer and Reason The function gets() reads characters from the stdin and stores them at the provided input buffer. However, gets() will keep reading until it encounters a newline character. Unless the buffer is large enough, or the length of the line being read is known ahead of time, gets() can potentially overflow the input buffer and start overwriting memory it is not supposed to, wreaking havoc or opening security vulnerabilities.
3rd Jan 2020, 11:18 AM
Gurpej Singh
Gurpej Singh - avatar
+ 6
Because gets() does not take any limit as parameter and doesn't have any pre-assigned range so that it can stop after a particular point. We therefore use fgets() to achieve the same with restricted range of input.
3rd Jan 2020, 11:11 AM
Avinesh
Avinesh - avatar