gets is dangerousThis tip submitted by carl johnson on 2006-07-21 13:13:35. It has been viewed 15374 times.
Rating of 6.0 with 157 votes
If we use this code:
char string[ 100 ]; printf("ENTER SENTENCE: "); gets(string);
we can introduce a bug or security vulnerability into our code!
The problem is that it allows someone to enter too much text and thereby overflow the buffer. There is no way for gets to know how big the string is supposed to be, so it will just read data until the user hits enter, even if it's way more than 100 characters. You can read more about the security risk of gets here. You can use fgets instead, which takes both a size for the string, ensuring there is no buffer overflow.
If you're interested in learning more about secure coding practices, check out this article on writing secure code.
Help your fellow programmers! Add a tip!