Why may an overflow occur in the following program?

好久不见. 提交于 2019-12-08 15:58:48

问题


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

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


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/45652970/why-may-an-overflow-occur-in-the-following-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!