this program uses gets(), which is unsafe.

Long time no come,This exercise,I encountered an interesting reminder:this program uses gets(), which is unsafe.


He says gets()function,He said fgets will()function。

fgets()Function is to read from the stream into the stream up to num characters in the character array str,When a line break、Or stop reading num-1 characters。And automatically add ' 0' null-terminated。

gets()Function is to read from standard input stdin a string,Wrap or the end of the encounter, when termination。Unlike fgets,He did not specify the num,It should be noted that the size of the character array str。
No relationship between macro definition and gets fgets,Each has its own implementation of each other。So why insecurity function gets it? Because the worm is to realize the function gets "credit"。Task gets function is to read in a string from the stream。It will tell the caller to read it into the string on what。but,gets()Function does not check the buffer size,If the caller provides a pointer to the stack pointer,And get()Function of the number of characters read into the buffer has exceeded the size of the space,get()Would happily extra characters will continue to write to the stack,This covers the original stack contents。

  1. int main(void)
  2. {
  3. char string[81];
  4. ……
  5. gets(string);

So that any extra data will be written to the stack。
In short,General recommendation is to use fgets()Completely replace the function gets()function。
Other:For various compilers gets()The attitude is not the same,Some will not compile directly blocked by,Some of them are tips,I use gcc is not directly prompt。But time is running terminal has suggested the use of this program gets function,perhaps,Gcc is to add a word of it!
At last,Part of the article borrows fromHere:)

Original article written by Gerber drop-off:R0uter's Blog » this program uses gets(), which is unsafe.

Reproduced Please keep the source and description link:

About the Author


The non-declaration,I have written articles are original,Reproduced, please indicate the link on this page and my name。

Leave a Reply

Your email address will not be published. Required fields are marked *