gets() is risky to use!
Consider the below program.
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.
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-
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.
Please Login to comment...