This article refers to the blog "12 interesting C language question and answer", on the basis of the original text added to the corresponding point of knowledge detailed introduction.
1 gets () method
Q: The following code has a hidden problem, can you find it?
1#include <stdio.h>2 3 intMainvoid)4 {5 Charbuff[Ten];6memset (Buff,0,sizeof(Buff));7 gets (buff);8printf"%s\n", buff);9 Ten return 0; One}
A: This inconspicuous problem is the use of the Gets () method, whose function prototype is as follows:
Char* gets (char *s);
This method accepts a character array parameter, but does not check if the array has enough space to copy the data. The Get () function is unsafe and deprecated, and in general the compiler gives a warning: the ' get ' function is dangerous and should not being used. Gets () does not check whether the reserved store can accommodate the data that is actually entered. The extra characters simply overflow into the adjacent storage area, which can cause errors.
So, here we generally use the fgets () method better, the function prototype is as follows:
Char* fgets (charint
The fgets () function is generally used to read the n-1 characters in the file into s , in fact, this function has a good use is to read the string from the standard input stream, And do not worry about the number of characters entered beyond the size of the character array, causing overflow problems! How do you do it? As follows:
Char str[];
It is worth noting that: remember that fgets () reads only n-1 characters . therefore,fgets () reads the newline character, the end of the file, or the n-1 characters that are returned.
12 interesting C-language quiz (detailed)