I have seen this code on a website and user who posted this code wanted to know about
the impact of fflush(stdin)
in this code. This is code below
main()
{
char *str1="string one";
char *str2="string two";
char charbuf; // store characters in buffer
puts("\nEnter first string");
gets(str1);
fflush(stdin); /*what does this mean here*/
while( (charbuf=getchar() ) != EOF && charbuf!='\n')
; // clear unwanted data
puts("\nEnter second string");
gets(str2);
fflush(stdin);/*what does this mean here*/
while( (charbuf=getchar() ) != EOF && charbuf!='\n')
;
for(;*str1==*str2&(*str1!='\0'||*str2!='\0\);str1++,str2++) ;
{
printf("\nthe string are equal");
}
else
{
printf("\nthe string are not equal");
}
return;
}
But for me before reaching to fflush(stdin) statement programmer already made a big mistake i.e. use of get(str1开发者_如何学JAVA);
Would it be ok to use gets(str1) here??
Flushing stdin
is undefined by the standard and therefore wrong. It is supposed to do that the following while
does: discard user input until (and including) \n
.
fflush(stdin);/*what does this mean here*/
It is never ok to use gets
since fgets
is always available and gets
will be removed from the next version of the standard.
Removal of the gets function, deprecated in the current C language standard revision, ISO/IEC 9899:1999/Cor.3:2007(E), in favor of a new safe alternative, gets_s
EDIT
Obviously since str1
and str2
point to string literals, they are not writable. Writing to them (via gets
or anything else) is undefined.
First, the fflush
of the stdin
causes an undefined behavior (thanks to Paul R. for the clarification).
Second, you're right, using gets
with a variable with an initial value is not correct. First, because the memory pointed by this variable may be just read only (DATA section of your program, that typically include read-only data); second, gets
may be beyond the ending of the string, causing memory corruption (for instance, overwriting other data stored in the DATA section following that string). Finally, the use of gets
is deprecated precisely for this reason: you cannot limit the extent of the string read.
To actually answer the question, rather than discuss the meaning (or lack thereof) of fflush() on a input stream:
The use of gets()
is never correct under any circumstances. There is no chance of being able to guarantee to avoid a buffer overflow.
You can use fgets()
instead as an almost direct and much safer alternative.
精彩评论