how has C bitten you? (and a sidetrack)

lam lam at btnix.UUCP
Fri Aug 23 20:48:29 AEST 1985



[*** The Phantom Article Gobbler Strikes Again ***]
> > > 	int i, a[10];
> > > 	for (i = 0; i <= 10; i++)
> > > 		a[i] = 0;
> > > 

> > This looks to me like it will simply overwrite one int's worth of
> > memory beyond the end of the array "a" with the value 0.  Granted,
> > depending on what happens to be after "a", this can have disastrous
> > results, but is there really an implementation in which it will
> > (reliably) lead to infinte looping?
> ----------
> Yes.  Any implementation that allocates the space for i following the
> space for a.

The cause of the infinite loop is due to the storage allocation.
	i.e.	&i == &a[10]
   causing i to be overwritten with 0 when i is 10.

The more interesting thing is that on some compilers, the infinite
   loop does NOT occur.  Lo and behold, the OPTIMISER comes into play.
   If i is put in a Register at the start of the for(), a[10] = 0 
   will indeed overwrite i in memory but not the register !!! and the
   loop terminates normally.
   What's worse, the optimiser has in this case hidden a program bug!!!

Thus the moral:

	"Don't just test your code once.  Test it again, this time
    	 turn the optimiser OFF first".

------------------------------------------------------------------
	Onward Lam 
	CAP Group, Reading, England.



More information about the Comp.lang.c mailing list