What is gets() in C?
gets() is a function declared in <stdio.h>. It reads characters from standard input and stores them in the character array you pass in. It stops when it reads a newline or reaches end of file. The newline is not stored, and a null character is added at the end.
It is called like this:
#include <stdio.h>
int main(void) {
char name[20];
printf("Enter your name: ");
gets(name);
printf("Hello, %s\n", name);
return 0;
}
The function takes only the array, with no size argument. It has no way to know that name holds just 20 characters.
Why gets() is unsafe
gets() keeps writing until it sees a newline. If the user types more than 19 characters, the extra characters go past the end of name. A 20-character array needs one byte for the terminating null, so 19 characters is the most that fit safely. Writing past the end of an array is a buffer overflow. In C, it is undefined behavior. The program might crash, print strange output, or leave memory corrupted. An attacker can also use this kind of overflow to make a program behave in ways its author did not intend.
Because the function has no safe way to limit its input, the C11 standard removed gets(). Many modern compilers also warn when a program uses it.
Safer alternatives
fgets() takes the array size, so it can stop before it runs past the end:
#include <stdio.h>
#include <string.h>
int main(void) {
char name[20];
printf("Enter your name: ");
if (fgets(name, sizeof name, stdin) != NULL) {
name[strcspn(name, "\n")] = '\0'; // remove the newline, if present
printf("Hello, %s\n", name);
}
return 0;
}
fgets() keeps the newline when there is room for it, which is why this example removes it. Any characters that do not fit stay in the input for the next read.
scanf("%s", name) has the same problem as gets(), because it does not limit the number of characters it stores. A field width fixes that. For a 20-byte array, scanf("%19s", name) reads at most 19 characters, which leaves room for the null terminator.
Reading text in C++
In C++, std::getline reads into a std::string, which grows as needed. There is no fixed-size array to overflow:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "\n";
return 0;
}
Reading text input in C++ is covered in more detail in c input string.