Using fgets() instead of scanf() for strings
What you'll learn: How to prevent memory corruption and program crashes by using a safer alternative for reading user text.
The problem with scanf()
Imagine you have a small mailbox designed to hold exactly five letters. If a delivery person tries to jam fifty letters into it, the mailbox will burst, and the mail will spill onto the street, potentially blocking traffic or getting lost.
In C, using scanf("%s", buffer) is like having that fragile mailbox. scanf() does not check how much space your "mailbox" (the character array) actually has. If a user types 100 characters into a 10-character buffer, C will faithfully try to write all 100 characters into memory. This is called a buffer overflow. It overwrites neighboring data, leading to weird bugs or malicious security exploits.
The fgets() solution
To program defensively, we use fgets(). This function is like a mailbox with a smart slot that only accepts a specific number of letters and rejects the rest. It requires three pieces of information: where to store the text, how many characters are allowed, and where the data is coming from.
#include <stdio.h>
int main() {
char name[10];
printf("Enter your name: ");
// Safety first: We tell fgets the limit is 10
// stdin means "Standard Input" (the keyboard)
fgets(name, 10, stdin);
printf("Hello, %s", name);
return 0;
}
Why it is safer
In the code above, even if the user types a name that is 50 characters long, fgets() will only grab the first 9 characters and leave a spot for the null terminator (\0). Your program remains stable because it never writes into memory it doesn't own.
One small quirk to remember: fgets() often keeps the "Enter" key (newline character \n) as part of the string if there is room. While you might need to trim that newline later, it is a small price to pay for a program that won't crash when a user types more than you expected.
Key takeaway
Always use fgets() for string input because it allows you to set a hard limit on how much data is written to your memory.