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?
GCC is a compiler for C language that can be used to compile C code. It creates an executable after compiling that can be executed directly. GDB is a debugger that can debug code in many languages like C, C++, Objective-C, etc.
Debugging is a methodical process of finding and reducing the number of bugs (or defects) in a computer program, thus making it behave as originally expected. There are two main types of errors that need debugging: ▶ Compile-time: These occur due to misuse of language constructs, such as syntax errors.
Compared to other programming languages, C can be a more difficult language to debug and figure out errors within code, no matter if it is logic or syntax-based.
a+b
may overflow if the sum of a
and b
is larger than UINT_MAX
, the maximum value for an unsigned int
. E.g.,
unsigned a = 1;
unsigned b = UINT_MAX;
printf("%u\n", (a+b)/2);
prints 0
.
If you want to find the average of two unsigned int
s without overflow, do
c = a/2 + b/2 + (a % 2 & b % 2);
(or (a%2 + b%2)/2
, or (a%2 && b%2)
, or ((a&1) & (b&1))
, etc.)
If a
and/or b
are very large then a + b
could exceed the maximum size of an unsigned integer (see MAX_UINT
in the limits.h
file). This would cause an overflow and so the result would be wrong. For example if a
and b
are 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:
c = a/2 + b/2 + (a % 2 == 1 && b % 2 == 1);
If you know that b
is greater than a
then you could use this slightly simpler version:
c = a + (b - a) / 2;
Read this article for information about how this bug appeared in binary search algorithms in may popular languages (though it talks about signed int
rather than unsigned int
):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With