Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Assuming that the precision of  signed char is 7 bits, and the precision of unsigned char is 8 bits, this operation is perfectly safe.  However, if the compiler represents the signed and unsigned char types using 31 and 32 bit precision (respectively), the variable uc would need be converted to unsigned int instead of signed int.  As a result of the usual arithmetic conversions, the signed int would then be converted to unsigned and the addition would take place between the two unsigned int values.   Also, because uc is equal to UCHAR_MAX which is equal to UINT_MAX in this example, the addition will result in an overflow.   The resulting value is then zero-extended to fit into the 64-bit storage allocated by sll.To ensure that integer values used as sizes, indices, loop counters, lengths, or in other circumstances

Non-compliant Code Example

The following code will result in an unsigned integer overflow during the addition of the unsigned operands ui1 and ui2. If this behavior is unanticipated, the resulting value may be used to allocate insufficient memory for a subsequent operation or in some other manner which could lead to an exploitable vulnerability.

Code Block

unsigned int sum;
unsigned int ui1 = UINT_MAX;
unsigned int ui2 = 1;

sum = ui1 + ui2;

Compliant Solution

The following compliant solution tests the suspect addition operation to guarantee there is no possibility of unsigned overflow. In this particular case, an overflow condition is present and the error_handler() method is invoked.

Code Block

unsigned int sum;
unsigned int ui1 = UINT_MAX;
unsigned int ui2 = 1;

if (~ui1 < ui2){
  error_handler("Overflow Error", NULL, EOVERFLOW);
}
sum = ui1 + ui2;