Course contentsShow
← C
Lesson 706 of 1,21910. Input and OutputFree lesson

The buffer size argument in fgets

The buffer size argument in fgets

What you'll learn: How to use the size argument in fgets to prevent your program from crashing when users type too much.

The "Overflow" Problem

In the early days of C, programmers often used a function called gets. It had one major flaw: it never knew when to stop. If you gave it a small bucket (a character array) and the user typed a giant waterfall of text, gets would just keep pouring until it spilled over, overwriting other important data in your computer's memory. This is called a buffer overflow, and it is a leading cause of software crashes and security hacks.

The Safety Guard

The fgets function solves this by requiring a "size" argument. Think of it like a bouncer at a club who knows exactly how many people are allowed inside. Even if a thousand people are waiting in line (the input), the bouncer only lets in enough to fill the room to its legal capacity.

Here is what the syntax looks like: fgets(buffer, size, stdin);

The size tells C: "This is the maximum number of characters my array can hold. Do not let one single byte more than this enter the building."

How C Counts Space

If you have an array of 10 characters, you should pass 10 as the size argument. However, fgets is smart—it saves one spot at the very end for the "null terminator" (\0), which tells C where the string ends.

If you tell fgets the limit is 10, it will read at most 9 characters from the user, then add the \0 at the end to keep things tidy.

#include <stdio.h>

int main() {
    // We have a small "bucket" that holds 10 characters
    char username[10];

    printf("Enter your name: ");

    // We pass '10' so fgets knows our limit.
    // Even if the user types "AlexanderTheGreat", 
    // it will only store "Alexander" + the null terminator.
    fgets(username, 10, stdin);

    printf("Safe result: %s\n", username);

    return 0;
}

Why This Matters

By always providing the correct size argument, you ensure your program is "memory safe." The function will stop reading as soon as it hits the limit, or as soon as it hits a newline (Enter key)—whichever comes first. It is a simple insurance policy against unpredictable user behavior.

Key takeaway

The size argument in fgets acts as a hard limit that prevents input from spilling over and crashing your program.