Reading safe strings with fgets
What you'll learn: How to use fgets() to read user text without risking memory crashes or security vulnerabilities.
The problem with scanf
Up until now, you might have used scanf("%s", buffer) to get text from a user. However, scanf is dangerous. It is like a water hose that doesn't know when the bucket is full; if a user types 100 characters into a space meant for only 10, scanf will keep writing data anyway. This "overflows" into memory it doesn't own, causing your program to crash or allowing hackers to take control.
Enter fgets: The safety gate
The fgets() function is the professional way to read strings. It requires you to specify a maximum limit, ensuring the program never "overflows the bucket." It stands for "file get string," and it takes three ingredients (arguments):
- Where to store it: Your character array (the buffer).
- How much to store: The size of that array.
- Where to get it from: Usually
stdin(Standard Input), which represents your keyboard.
Coding it safely
Here is how you implement fgets in a real program:
#include <stdio.h>
int main() {
char name[20];
printf("Enter your full name: ");
// fgets(array, size, source)
// It will read up to 19 characters, leaving room for the null terminator \0
fgets(name, sizeof(name), stdin);
printf("Hello, %s", name);
return 0;
}
The "Newline" quirk
There is one tiny catch: fgets is very polite—it stops reading when the user presses Enter, but it actually saves that "Enter" key (the \n character) into your string. If you type "Bob" and hit Enter, your string becomes "Bob\n".
Unlike scanf, which stops at the first space, fgets will happily read an entire sentence, spaces and all, until it hits the size limit or the user presses Enter. This makes it the superior choice for reading names, addresses, or any text where safety and spaces matter.
Key takeaway
Use fgets(buffer, sizeof(buffer), stdin) instead of scanf to prevent buffer overflows and safely capture spaces in user input.