...
This noncompliant code example may result in an unsigned integer wrap during the addition of the unsigned operands ui1
and ui2
ui_a
and ui_b
. 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 | ||||
---|---|---|---|---|
| ||||
unsigned int ui1, ui2,ui_a; unsigned int ui_b; unsigned int usum; /* Initialize ui1ui_a and ui2ui_b */ usum = ui1ui_a + ui2ui_b; |
Compliant Solution (Precondition Test)
...
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1, ui2,ui_a; unsigned int ui_b; unsigned int usum; /* Initialize ui1ui_a and ui2ui_b */ if (UINT_MAX - ui1ui_a < ui2ui_b) { /* handle error condition */ } else { usum = ui1ui_a + ui2ui_b; } |
Compliant Solution (Postcondition Test)
...
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1, ui2,ui_a; unsigned int ui_b; unsigned int usum; /* Initialize ui1ui_a and ui2ui_b */ usum = ui1ui_a + ui2ui_b; if (usum < ui1ui_a) { /* handle error condition */ } |
...
This noncompliant code example may result in an unsigned integer wrap during the subtraction of the unsigned operands ui1
and ui2
ui_a
and ui_b
. If this behavior is unanticipated, it may lead to an exploitable vulnerability.
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui_a; unsigned int ui1, ui2,ui_b; unsigned int udiff; /* Initialize ui1ui_a and ui2ui_b */ udiff = ui1ui_a - ui2ui_b; |
Compliant Solution (Precondition Test)
...
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui_a; unsigned int ui1, ui2,ui_b; unsigned int udiff; /* Initialize ui1ui_a and ui2ui_b */ if (ui1ui_a < ui2ui_b){ /* handle error condition */ } else { udiff = ui1ui_a - ui2ui_b; } |
Compliant Solution (Postcondition Test)
...
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui_a; unsigned int ui1, ui2,ui_b; unsigned int udiff ; /* Initialize ui1ui_a and ui2ui_b */ udiff = ui1ui_a - ui2ui_b; if (udiff > ui1ui_a) { /* handle error condition */ } |
...
This noncompliant code example using atomic integers can result in unsigned integer overflow wrapping:
Code Block |
---|
atomic_int i; int ui1ui_a; /* Initialize i, ui1ui_a */ atomic_fetch_add(&i, ui1ui_a); |
Compliant Solution
This compliant solution performs a postcondition test to ensure that the result of the unsigned addition operation to i
is not less than the operand ui1
ui_a
:
Code Block |
---|
atomic_int i; int ui1ui_a; /* Initialize ui1ui_a, i */ atomic_fetch_add(&i, ui1ui_a); if (atomic_load(&i) < ui1ui_a) { /* handle error condition */ } |
Exceptions
...