Limiting string length in scanf
What you'll learn: How to prevent memory crashes by telling scanf exactly how many characters your variable can hold.
The Overflow Problem
Imagine you have a small physical mailbox designed to hold exactly 10 letters. If a mail carrier tries to cram 50 letters into it, the mailbox will burst, and the extra mail will spill onto the floor, potentially blocking your doorway or getting lost.
In C, when you use scanf("%s", buffer), you are telling the computer to take whatever the user types and shove it into your variable. By default, %s is "greedy"—it will keep reading until it hits a space or a newline. If the user types a 100-character sentence but your variable only has room for 10 characters, scanf will overwrite the memory next to your variable. This is called a buffer overflow, and it is one of the most common ways programs crash or get hacked.
Setting the Limit
To fix this, you add a number between the % and the s. This number tells C the maximum number of characters to read.
Crucial Rule: Always reserve one extra spot for the "null terminator" (\0), which C uses to mark the end of a string. If your array size is 20, you should tell scanf to read a maximum of 19.
#include <stdio.h>
int main() {
// We create a "bucket" that holds 10 characters
char username[10];
printf("Enter a username (max 9 chars): ");
/*
We use %9s. This tells scanf:
"Grab up to 9 characters. If the user types more,
stop anyway and leave room for the \0 at the end."
*/
scanf("%9s", username);
printf("Stored name: %s\n", username);
return 0;
}
Why this matters
By using %9s instead of %s, you’ve built a safety gate. If a user tries to enter a massive string of 500 characters, scanf will simply take the first 9, stop, and place the null terminator in the 10th slot. Your program stays stable, your memory stays clean, and the "extra mail" simply stays in the input buffer rather than breaking your mailbox.
Key takeaway
Always use a width limit (like %9s) with scanf to ensure the input never exceeds the size of your character array.