...
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 |
---|
|
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 |
---|
|
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 |
---|
|
unsigned int ui1, sumui2, usum;
/* Initialize ui1 and ui2 */
usum = ui1 + ui2;
if (usum < ui1 || usum < ui2) {
/* handle error condition */
}
|
...
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 |
---|
|
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 |
---|
|
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 |
---|
|
unsigned int ui1, ui2, udiff ;
/* Initialize resultui1 and ui2 */
udiff = ui1 - ui2;
if (udiff > ui1 || udiff > ui2) {
/* handle error condition */
}
|
Anchor |
---|
| Multiplication |
---|
| Multiplication |
---|
|
...