What You Should Not Do

Not checking the size or range of integer values input or stored in a program. This can cause indeterminate behavior or program failure.

unsigned short j = 65535;
...
j++;
...
if (j < 500)
{
    grant access to file X;
}

The range of an unsigned short int is 0 to 65,535. What happens if j is somehow changed to a value greater than 65,535? It loops back around beginning at 0 which may result in an incorrect file acesss.

What You Should Do

Checking or verifying integer values that can be set beyond the intended range or the range of the type. The key to this error is where and how j is set. If it is not possible to incorrectly set j, then the code will be safe. However, it is still a good programming practice to verify that a given value is in the intended range.

unsigned short j;
...
j++;
...
if(j < 65535) j++; else error!
if (j < 500)
{
  grant access to file X;
}

Concept Map

This example refers to the point M (Be wary of off by one errors).This maps to "Bad Code" in the concept map.

 

JSN Teki template designed by JoomlaShine.com