C Tutorial Int overflow
Introduction to C language
Integer types
Char constants
Int constants
Type combination and promotion
Int overflow
Floating point types
Comments
Variables
Assignment operator
Truncation
Int vs float arithmatic
Mathematical operators
Unary Increment Operators
Pre and Post Variations
C Programming Cleverness and Ego Issues
Relational Operators
Logical Operators
Bitwise Operators
Other Assignment Operators

 

 
 
 
 

 

HOME
 

Once some body  had a piece of code which tried to compute the number of bytes in a buffer with

the expression (k * 1024) where k was an int representing the number of kilobytes

I wanted. Unfortunately this was on a machine where int happened to be 16 bits. Since

k and 1024 were both int, there was no promotion. For values of k >= 32, the product

was too big to fit in the 16 bit int resulting in an overflow. The compiler can do

whatever it wants in overflow situations -- typically the high order bits just vanish. One

way to fix the code was to rewrite it as (k * 1024L) -- the long constant forced the promotion of the int. This was not a fun bug to track down -- the expression sure looked reasonable in the source code. Only stepping past the key line in the debugger showed the overflow problem. "Professional Programmer's Language." This example also

demonstrates the way that C only promotes based on the types in an expression. The compiler does not consider the values 32 or 1024 to realize that the operation will overflow (in general, the values don't exist until run time anyway). The compiler just

looks at the compile time types, int and int in this case, and thinks everything is fine.

 

Want more information and Video ???