Why gets is dangerous and deprecated
What you'll learn: Why the gets() function is a major security risk and why you should never use it in modern C programming.
The "Open Door" Problem
Imagine you are hosting a party in a room that fits exactly 10 people. You tell a security guard, "Let people in until they stop coming." You don't tell the guard to stop at 10. If 50 people show up, they will crush the furniture, break the walls, and spill into the restricted offices next door.
This is exactly how the gets() function works. When you provide a character array (a buffer) to gets(), you are telling C to keep reading input until the user hits the "Enter" key. The function has no idea how large your array is. It blindly pours data into memory, even if that data exceeds the space you allocated.
The Buffer Overflow
When you provide more input than a buffer can hold, it results in a buffer overflow. The extra data doesn't just disappear; it overwrites adjacent memory. This can crash your program, but more dangerously, it can be exploited by hackers to inject malicious code into your computer's memory.
Because of this fundamental flaw, gets() was officially removed from the C standard in 2011. Using it today will often trigger a compiler warning—or even an error—telling you that the function is "deprecated" (obsolete and unsafe).
A Dangerous Example
Look at the code below. Even though we only set aside 10 bytes, gets() will happily try to cram 100 characters into that tiny space if the user types them.
#include <stdio.h>
int main() {
char username[10];
printf("Enter your name: ");
// DANGER: gets() does not know username only holds 10 chars
gets(username);
printf("Hello, %s!\n", username);
return 0;
}
If a user types a very long string, the program might overwrite its own return address, leading to a total security breach. In future lessons, we will use fgets() or scanf() with width limits, both of which allow you to specify the maximum number of characters to read, keeping your "room" safe from overcrowding.
Key takeaway
Never use gets(); it cannot check for buffer limits, making your programs vulnerable to crashes and security exploits.