Integer Overflow

 

In C an int is stored in 32 bits, and the maximum value is 231-1, approximately 2.1 ´ 109. If during a calculation an integer result is bigger than this maximum then integer overflow occurs. Unfortunately, in C, this overflow is not reported and the result will be incorrect. Let’s demonstrate what happens in this C program:

 

int a = 110000, b = 120000;

printf( "%d\n", a*b );

 

When this is run the number 315098112 is printed.

 

Here is an explanation. First note that 110000 * 120000 = 13200000000 is bigger than 231-1. Only the last 32 bits of the result are kept. The binary value of 13200000000 (using MS Calculator’s bin and dec) is:

 

1100010010110010000000010000000000

 

and the last 32 bits are:

 

00010010110010000000010000000000.

 

Converting this binary number to decimal gives 315098112.

 

Another demonstration shows that a negative number can also be obtained. If we multiply 80000 and 90000 in a C program we get the negative number, -1389934592. In this case 7200000000 in binary is:

 

110101101001001110100100000000000

 

and the last 32 bits are:

 

10101101001001110100100000000000.

 

Because the first bit is 1 this represents a negative number. (In the first example the first bit was 0, so represents  a positive number or zero.) Negative numbers are represented using 2's complement - see Appendix C of the textbook. To find the number in decimal, first subtract 1:

 

10101101001001110100011111111111

 

and then "flip" each bit, i.e. change each 1 to 0, and each 0 to 1:

 

01010010110110001011100000000000.

 

Convert this to base 10 to get 1389934592, so the negative number is -1389934592.

 

The moral is to ensure that the numbers involved in C calculations using int are not too big, otherwise results will be incorrect.