Consider the below program.
C
void read(){ char str[20]; gets(str); printf("%s", str); return;} |
The code looks simple, it reads string from standard input and prints the entered string, but it suffers from Buffer Overflow as gets() doesn’t do any array bound testing. gets() keeps on reading until it sees a newline character.
To avoid Buffer Overflow, fgets() should be used instead of gets() as fgets() makes sure that not more than MAX_LIMIT characters are read.
C
#define MAX_LIMIT 20void read(){ char str[MAX_LIMIT]; fgets(str, MAX_LIMIT, stdin); printf("%s", str); getchar(); return;} |
NOTE: fgets() stores the ‘\n’ character if it is read, so removing that has to be done explicitly by the programmer. It is hence, generally advised that your str can store at least (MAX_LIMIT + 1) characters if your intention is to keep the newline character. This is done so there is enough space for the null terminating character ‘\0’ to be added at the end of the string.
If keeping the newline character is not intended, then one can simply do the following-
C
int len = strlen(str);// Remove the '\n' character and replace it with '\0'str[len - 1] = '\0'; |
Please feel free to read more about gets() and fgets() here.
Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Problem with scanf() when there is fgets()/gets()/scanf() after it
- fgets() and gets() in C language
- Difference between scanf() and gets() in C
- Modify the string such that every character gets replaced with the next character in the keyboard
- scanf("%[^\n]s", str) Vs gets(str) in C with Examples
- Do not use sizeof for array parameters
- Can we use function on left side of an expression in C and C++?
- What is use of %n in printf() ?
- Use of realloc()
- When do we use Initializer List in C++?
- Use of explicit keyword in C++
- How to use getline() in C++ when there are blank lines in input?
- How to use SQLMAP to test a website for SQL Injection vulnerability
- Use of fflush(stdin) in C
- How to use POSIX semaphores in C language
- Use of & in scanf() but not in printf()
- Why strcpy and strncpy are not safe to use?
- Use of FLAG in programming
- Why to use fgets() over scanf() in C?
- What is JavaDoc tool and how to use it?
Improved By : priyanshulgovil

