gets is dangerous

This tip submitted by carl johnson on 2006-07-21 13:13:35. It has been viewed 18891 times.
Rating of 5.3 with 182 votes

If we use this code:

char string[ 100 ];
printf("ENTER SENTENCE: "); 

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.

More tips

Help your fellow programmers! Add a tip!