While reading some question on a site I came across below question where a c question needs to be debug
unsigned int a, b, c;
/* a and b are assume to have some values */
c = (a + b) / 2; // <- There is a bug in this st
What is the bug? and how you debug it?
Some of the answer saying it could cause overflow(c=(a+b)/2).but really didn’t get how it cause overflow?
If
aand/orbare very large thena + bcould exceed the maximum size of an unsigned integer (seeMAX_UINTin thelimits.hfile). This would cause an overflow and so the result would be wrong. For example ifaandbare both equal to 0x80000000 the result would be 0 in 32-bit arithmetic, rather than expected result 0x80000000.To solve it you could use something like this instead:
If you know that
bis greater thanathen you could use this slightly simpler version:Read this article for information about how this bug appeared in binary search algorithms in may popular languages (though it talks about
signed intrather thanunsigned int):