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

Safe input reading with `fgets`

Safe input reading with fgets

What you'll learn: How to prevent program crashes and security holes by using fgets() instead of the dangerous scanf() for reading text.

The problem with the "Open Door"

Imagine you are hosting a party and tell your friend, "Hey, bring some snacks over." If your friend shows up with a single bag of chips, everything is fine. But what if they show up with a literal dump truck full of popcorn? If your house isn't big enough to hold it, the walls will burst.

In C, the scanf("%s", buffer) function is that open door. It keeps taking input until it hits a space or a new line, regardless of how small your "house" (the array) is. If a user types 100 characters into a 10-character array, the extra data overflows into other parts of your computer's memory. This is called a buffer overflow, and it is one of the leading causes of software crashes and hacking vulnerabilities.

The safety guard: fgets()

The fgets() function acts like a bouncer at the door. You tell the bouncer exactly how many people are allowed inside. If more show up, the bouncer simply stops them at the limit, keeping your house intact.

Here is how you use it safely:

#include <stdio.h>

int main() {
    char name[20];

    printf("Enter your name: ");
    
    // fgets(array_name, size_limit, source)
    // stdin means "standard input" (the keyboard)
    fgets(name, sizeof(name), stdin);

    printf("Hello, %s", name);

    return 0;
}

Why it works

When you use fgets(name, sizeof(name), stdin), you are giving the function three pieces of information:

  1. Where to put the data: The name array.
  2. The maximum capacity: sizeof(name) tells C to read no more than 19 characters (leaving 1 spot for the null terminator \0).
  3. Where to get it: stdin is the shortcut for your keyboard.

If the user types a name that is 50 characters long, fgets will safely grab the first 19, add the terminator, and ignore the rest. Your program remains stable, your memory stays clean, and your "house" doesn't burst.

Key takeaway

Always use fgets() instead of scanf() for strings because it lets you set a hard limit on input size, preventing memory corruption.