Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 396
Tom Avatar asked Aug 12 '17 17:08

Tom


People also ask

Why do overflows happen?

An integer overflow or wraparound happens when an attempt is made to store a value that is too large for an integer type. The range of values that can be stored in an integer type is better represented as a circular number line that wraps around.

What can happen in a program if a value overflows?

An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in −128, a two's complement of 128).

What happens when overflow occurs in C?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).

How overflow and underflow errors occur in programming?

Simply put, overflow and underflow happen when we assign a value that is out of range of the declared data type of the variable. If the (absolute) value is too big, we call it overflow, if the value is too small, we call it underflow.


1 Answers

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
like image 87
Sergey Kalinichenko Avatar answered Sep 28 '22 08:09

Sergey Kalinichenko