Tom
Tom

Reputation: 934

Why may an overflow occur in the following program?

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

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

Upvotes: 9

Views: 527

Answers (3)

Gilbert
Gilbert

Reputation: 3776

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.

Upvotes: 1

Kashif Faraz Shamsi
Kashif Faraz Shamsi

Reputation: 511

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.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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

Upvotes: 13

Related Questions