Handling the scanf buffer overflow
What you'll learn: How to prevent your program from crashing or being hacked by limiting how much data scanf reads into a string.
The "Overflowing Suitcase" Problem
Imagine you have a small suitcase that can hold exactly five shirts. If you try to force ten shirts into it, the suitcase will burst, and your clothes will spill all over the floor, creating a mess.
In C, a character array (a string) is like that suitcase. If you create an array of 10 characters but use scanf("%s", myString) to read a 50-character word, scanf doesn't know when to stop. It will keep writing those extra characters into memory locations it doesn't own. This is called a buffer overflow. It can crash your program, corrupt other variables, or even allow hackers to take control of your computer.
The Safety Guard: Width Specifiers
To fix this, we use a "width specifier." By placing a number between the % and the s in your format string, you tell scanf exactly how many characters it is allowed to store.
If your array size is N, you should set the width to N-1. Why minus one? Because every string in C needs a hidden "null terminator" (\0) at the very end to mark where the text stops. If your array is 10 bytes, you can only fit 9 letters plus the null terminator.
Defensive Coding in Action
Here is how you write a safe input statement:
#include <stdio.h>
int main() {
// We have room for 9 characters + the null terminator
char username[10];
printf("Enter your username (max 9 chars): ");
// The %9s limits input to 9 characters
// Any extra characters will stay in the input buffer
scanf("%9s", username);
printf("Safe input received: %s\n", username);
return 0;
}
By adding that 9, you’ve built a wall. If a user types a 100-character name, scanf will gracefully grab the first nine, add the \0 to the tenth slot, and stop. Your suitcase stays intact, and your program stays stable.
Key takeaway
Always include a maximum width in your scanf string format (like %9s) to match your array size minus one.