Note: I'm in an introduction to programming class, any feedback is appreciated.
I've been able to reproduce a problem in Pelles C wherein an infinite loop occurs in the compiled console program built from a source under the following circumstances:
- A "while" loop is used, or a "do while" loop is used.
- A scanf function is used inside the loop.
- The scanf function returns zero
The loop effectively skips the statement containing the scanf function altogether in repetitions of the loop.
-- (Edit: thereby causing an infinite loop)
I initially thought that the defect only occurs if scanf returns a value to a variable (int) that I assigned... however, this is not always true, even when scanf is compared to a constant, it screws up:
Cases when scanf will faulter:
//the most obvious and common case
int x;
x = scanf("%i",x);
//the most annoying case (since the majority of the class is likely using the following mechanism in an attempt to handle erroneous input)
int x;
int xtype;
xtype=0;
while (xtype==0)
{
xtype=scanf("%i",x);
}
//the even more annoying part of this case is that using the fflush function to remove erroneous input fails to do the job as in
int x;
int xtype;
xtype=0;
while (xtype==0)
{
fflush(stdin);
xtype=scanf("%i",x);
}
Note that the fflush can occur before or after the scanf, it really doesn't descriminate after it enters into the loop.
//the final case and one that took a bit of research for me to do to finally locate on the official gnu site is also quite irritating:
int x;
int xtype;
xtype=0;
do {
fflush(stdin);
} while (scanf("%i",x)==0);
//I haven't tried the following and final case, but I'm pretty sure it doesn't work either. Note that the presence of fflush matters not.
int x;
int xtype;
xtype=0;
while (scanf("%i",x)==0);
{
fflush(stdin);
}
-- (Edit: The underneath was new)
I suppose this bug is associated with another bug I've verified in Pelles C:
If there are multiple scanf's is a sequence, and data entered is incompatible with one variable due to its type, the data is passed from one scanf downstream to the next--
This is usually preventable with fflush, HOWEVER, fflush does nothing in Pelles.
Thanks,
Ed