Versions Compared

Key

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

...

This noncompliant code example may result in an unsigned integer wrap during the addition of the unsigned operands ui1 and ui2. If this behavior is unexpected, the resulting value may be used to allocate insufficient memory for a subsequent operation or in some other manner that can lead to an exploitable vulnerability.

Code Block
bgColor#FFcccc

unsigned int ui1, ui2, sumusum;

/* Initialize ui1 and ui2 */

sumusum = ui1 + ui2;

Compliant Solution

This compliant solution tests performs a pre-condition test of the operands of the addition to guarantee there is no possibility of unsigned wrap.

Code Block
bgColor#ccccff

unsigned int ui1, ui2, sumusum;

/* Initialize ui1 and ui2 */

if (UINT_MAX - ui1 < ui2) {
  /* handle error condition */
}
else {
  usum = ui1 + ui2;
}

This compliant solution performs a post-condition test to ensure that the result is not less than either of the operands.

Code Block
bgColor#ccccff
unsigned int ui1,  sumui2, usum;

/* Initialize ui1 and ui2 */

usum = ui1 + ui2;
if (usum < ui1 || usum < ui2) {
  /* handle error condition */
}

Anchor
Subtraction
Subtraction

...

This noncompliant code example may result in an unsigned integer wrap during the subtraction of the unsigned operands ui1 and ui2. If this behavior is unanticipated, it may lead to an exploitable vulnerability.

Code Block
bgColor#FFcccc

unsigned int ui1, ui2, resultudiff;

/* Initialize ui1 and ui2 */

resultudiff = ui1 - ui2;

Compliant Solution

This compliant solution tests the unsigned operands of the subtraction to guarantee there is no possibility of unsigned wrap.

Code Block
bgColor#ccccff

unsigned int ui1, ui2, resultudiff;

/* Initialize ui1 and ui2 */

if (ui1 < ui2){
   /* handle error condition */
}
else {
  udiff = ui1 - ui2;
}

This compliant solution tests the unsigned operands of the subtraction to guarantee there is no possibility of unsigned wrap.

Code Block
bgColor#ccccff

unsigned int ui1, ui2, udiff ;

/* Initialize  resultui1 and ui2 */

udiff = ui1 - ui2;
if (udiff > ui1 || udiff > ui2) {
  /* handle error condition */
}

Anchor
Multiplication
Multiplication

...