gets() is risky to use!
Consider the below program.
void read() { char str[20]; gets(str); printf("%s", str); return; } |
chevron_right
filter_none
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.
#define MAX_LIMIT 20 void read() { char str[MAX_LIMIT]; fgets(str, MAX_LIMIT, stdin); printf("%s", str); getchar(); return; } |
chevron_right
filter_none
Please write comments if you find anything incorrect in the above article, or you want to share more information about the topic discussed above.
Recommended Posts:
- C/C++ if else statement with Examples
- Internal static variable vs. External static variable with Examples in C
- C/C++ if statement with Examples
- C/C++ do while loop with Examples
- C/C++ while loop with Examples
- C/C++ if else if ladder with Examples
- Difference between Static variables and Register variables in C
- C fopen() function with Examples
- C/C++ For loop with Examples
- Modify the string such that every character gets replaced with the next character in the keyboard
- Length of the longest subsegment which is UpDown after inserting atmost one integer
- Artificial Intelligence in Robotics
- Arrow operator -> in C/C++ with Examples
- return statement in C/C++ with Examples



