If used once, saw the warning and continued using, you are making a mistake.
Buffer overflow
The gets()
function receives a variable that functions as a buffer . That is, a variable is created and passed to the function that will put a value on it. When the variable is created, it has a specific size. This function has no measure to ensure that the value does not exceed the size of the variable. The C language itself does not have mechanisms that guarantee the limit of the variable.
The buffer overflow occurs when the value obtained (at device read) is greater than the size of the variable. Then the function writes in an area that is reserved for something else. Being able to write where it should not, it allows the execution to be tampered with and the code does something unexpected, opening up security holes.
"Hackers" take advantage of this failure to send data that they know will overwrite memory improperly. Understanding the memory positions that the application will be using in a given situation, it can send a code or modify a data that will execute an undue code that is not part of the expected operation in the application, such as enabling a login even without a correct password.
Solution
The great advantage of the fgets()
function and other similar is that one of its parameters says the size of the buffer and the function ensures that it will not exceed this limit, even if the value it receives is larger. This way the data can not interfere with other areas of memory.
Other dangerous functions
Be careful also (follow the "safe" alternative already in the default):
-
strcpy()
- > strncpy()
-
strcat()
- > strncat()
-
strlen()
- > strnlen()
-
strcmp()
- > strncmp()
-
strdup()
- > strndup()
-
wcscpy()
- > wcsncpy()
-
wcslen()
- > wcsnlen()
-
sprintf()
- > snprintf()
Other things that can be bad in some situations: - scanf()
, getwd()
, realpath()
atoi()
, memcpy()
, strtok()
Some of these functions have dangerous variations as well. Note that the alternative is not guaranteed to be safe, they just have a slightly better mechanism. They do not replace their correct use and additional checks.
Some are dangerous and prone to buffer only if misused. gets()
is really dangerous no matter what the programmer does.
Obviously I will not risk saying this is a complete list.