Thursday, June 04, 2009

What’s wrong with this code?

image

The breakpoint at line 18 never hits.

This is a really silly bug :D.

Leave comments if you know what is wrong.

2 comments:

trahho said...

Well, i is declared as byte, and since the CLR doesn't do any overflow check it just goes from 255 to 0 and never reaches 375.

This gives a very nice infinite loop.

By the way, I don't think it's a silly mistake! Here it's easy to spot, but if the increment happens "deep down inside" some complex call graph it's really hard to track.

I wonder how often one could find this bug in production code...

Krishna Bhargava Vangapandu said...

http://msdn.microsoft.com/en-us/library/hy48x9zb.aspx

The compiler generates a warning (CS0652) notifying the overflow but I guess I did not look at it until now.

There is also an FxCop rule "Operators should not overflow" but I am somehow not able to make that rule pop up. I shall look into this and update pretty soon.