Thursday, September 1, 2011

Catch the Bug - 1

After a long time, I am restarting this blog.

Today I am introducing a programming bug.
Look at the pseudo code below.

unsigned long uCount;
unsigned long uMaxVal;

....
....

//uMaxVal assigned some unsigned value here
....

for(uCount = 0; uCount < uMaxVal -1; uCount++)
{

 //Do whatever
}


Do you find anything wrong on seeing this simple statements? You thinks the loop will terminates when the uCount value reaches the uMaxVal.


What if uMaxVal value is 0.

You simply says the program control will not enter in to the for loop. But it is false.

What is the value of (nMaxVal -1) when nMaxVal is equals to zero.

If you Answer '-1' it is Wrong.

Since it is a Unsigned Long value, it does not return -1, instead it returns the maximum value of the long datatype. For a 32 bit compiler it returns '4294967295' as a results. So the program control enters into the for loop and it iterates until uCount reaches the maximum value.

So, beware of using unsigned values.

This is not an infinte loop bug, it terminates once the max value  but the behavior of the program is undefined.