9
void main () {
  int i;
  if (i < 0) { i = -i; };
}

Can anyone help me to understand why an overflow may occur in the above program?

Floern
  • 33,559
  • 24
  • 104
  • 119
Tom
  • 904
  • 1
  • 7
  • 21

3 Answers3

13

An overflow may occur because the range of integer representation in two's complement is not symmetric: the magnitude of the smallest negative number that can be represented is the magnitude of the highest positive number that can be represented, plus one. For example, on a 32-bit system the values are -2,147,483,648 and 2,147,483,647. That's why negating -2,147,483,648 would result in an overflow: the result of negation, a positive value 2,147,483,648, cannot be represented in an int of the same size.

Note that the inverse of this problem is not true: negating a positive number would not result in an overflow:

if (i > 0) { i = -i; } // No overflow here
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Your value of "i", in the stack, is undefined when main starts. The start-up code that runs before main() is called can leave anything there.

Addig to that what Kashif said, negative integers can go one value lower than non-negative integers as negatives don't need to leave room for zero. A "1" in the sign bit, with all remaining bits zero, causes an overflow when sign reversed.

In 16 bits: -0x8000 == ~0x8000 + 1 == 0x7FFF + 1 == 0x8000
// "-" negative value == invert + 1 == inverted + 1 == final is the same

The likely hood of this value is low, but present. It will not happen unless the stack just happens to contain the offending number.

Gilbert
  • 3,740
  • 17
  • 19
0

The cause for an integer overflow is when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits, either larger than the maximum or lower than the minimum representable value.

  • Well, in your case the variable i is not initialized. So what will happen here is that the memory space which is assigned to variable i of integer type will be containing some garbage value.
  • If by any chance that memory address contains the maximum possible integer value which is -2^31(-2,147,483,648) then negating this value will result in integer overflow.

I hope this helps.

Kashif Faraz Shamsi
  • 513
  • 1
  • 7
  • 21