Why gets() is strictly forbidden
What you'll learn: Why the gets() function is a dangerous security risk and how it can crash your program through buffer overflows.
The "Infinite Bucket" Problem
Imagine you have a small physical bucket that can hold exactly 5 gallons of water. You tell a robot, "Fill this bucket with water from the hose." If the robot doesn't know how to stop when the bucket is full, it will keep pouring. Water will spill over the sides, soak your floor, ruin your carpet, and perhaps short-circuit your electronics.
In C programming, gets() is that mindless robot. When you use gets(), you provide a "bucket" (a char array), but the function has no way of knowing how large that array is. It will keep reading characters from the keyboard until the user presses Enter, regardless of whether you have space to store them.
Memory Corruption in Action
In C, variables sit next to each other in your computer's memory. If you overflow one variable, you aren't just losing data; you are overwriting the data belonging to other parts of your program.
#include <stdio.h>
int main() {
char password_protected = 'N'; // A secret flag
char username[8]; // Space for only 7 letters + null terminator
printf("Enter username: ");
// DANGER: gets() does not check the size of username!
gets(username);
if (password_protected == 'Y') {
printf("Access Granted!\n");
} else {
printf("Access Denied.\n");
}
return 0;
}
If a user types "Administrator", which is 13 characters long, gets() will happily shove those extra letters into memory locations it doesn't own. It might overwrite the password_protected variable, changing 'N' to something else and accidentally "unlocking" the program. This is called a Buffer Overflow.
Why it is "Forbidden"
The gets() function is so dangerous that it was officially removed from the C standard in 2011. Modern compilers will often throw a warning or even an error if you try to use it. It is the primary tool used by hackers to inject malicious code into software.
Instead of gets(), always use fgets(). It requires you to specify the maximum number of characters to read, ensuring your "bucket" never overflows.
Key takeaway
Never use gets(); it cannot check for buffer limits and creates critical security vulnerabilities by overwriting adjacent memory.