Course contentsShow
← C
Lesson 432 of 1,2196. Arrays and StringsFree lesson

Why `gets` is dangerous and deprecated

Why gets is dangerous and deprecated

What you'll learn: Why the gets() function was removed from the C standard and why you should never use it in your code.

The "Bottomless Pit" Problem

Imagine you are a waiter at a restaurant. You provide a customer with a small breadbasket that holds exactly four rolls. You tell the customer, "Put as many rolls as you want in here," and then you close your eyes. If the customer tries to cram twenty rolls into that tiny basket, the basket will break, and rolls will spill all over the table, the floor, and the other customers' plates.

This is exactly what happens with the gets() function.

When you use gets(my_buffer), you are telling C to take whatever the user types and shove it into my_buffer. However, gets() has no idea how big my_buffer actually is. It will keep writing data until the user presses Enter, even if that data overflows the memory you allocated.

Why it is dangerous

In programming, this is called a Buffer Overflow. When gets() writes past the end of your array, it starts overwriting other important data in your computer's memory. This can lead to two major issues:

  1. Crashes: Your program might try to access memory it no longer owns, causing a "Segmentation Fault."
  2. Security Breaches: Hackers love gets(). By entering a very specific, long string of characters, they can overwrite the "return address" of a function. This allows them to trick the computer into running their own malicious code instead of yours.

Because of this inherent flaw, gets() was officially removed from the C standard in 2011. Most modern compilers will give you a loud warning or even an error if you try to use it.

The Safe Alternative: fgets

To stay safe, always use fgets(). Unlike its dangerous cousin, fgets() asks for the size of your "basket" before it starts filling it.

#include <stdio.h>

int main() {
    char username[10];

    printf("Enter your name: ");
    
    // SAFE: We tell fgets the limit is 10 bytes
    // It will stop reading before it overflows the array
    fgets(username, 10, stdin);

    printf("Hello, %s", username);
    return 0;
}

By specifying 10, you ensure that even if a user types 1,000 characters, your program will only grab what it can safely fit, keeping the rest of your memory secure.

Key takeaway

Never use gets() because it cannot check for buffer limits; use fgets() instead to keep your programs secure and stable.