In Fig. 4.7, line 54
total = total + grade; // add grade to total
added each grade
entered by the user to the total
. Even this simple statement has a potential problem—adding the integers could result in a value that’s too large to store in an int
variable. This is known as arithmetic overflow and causes undefined behavior, which can lead to unintended results (en.wikipedia.org/wiki/Integer_overflow#Security_ramifications
). Figure 2.5’s addition program had the same issue in line 19, which calculated the sum of two int
values entered by the user:
sum = number1 + number2; // add the numbers; store result in sum
The maximum and minimum values that can be stored in an int
variable are represented by the constants INT_MAX
and INT_MIN
, respectively, which are defined in the header <climits>
. There are similar constants for the other integral types and for floating-point types. You can see your platform’s values for these constants by opening the headers <climits>
and <cfloat>
in a text editor (you can search your file system for these files).
It’s considered a good practice to ensure that before you perform arithmetic calculations like the ones in line 54 of Fig. 4.7 and line 19 of Fig. 2.5, they will not overflow. The code for doing this is shown on the CERT website www.securecoding.cert.org
—just search for guideline “INT32-CPP.” The code uses the &&
(logical AND) and ||
(logical OR) operators, which are introduced in Chapter 5. In industrial-strength code, you should perform checks like these for all calculations.