...
This noncompliant code example can result in a divide-by-zero error during the division of the signed operands sl1
and sl2
s_a
and s_b
:
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1s_a; signed long sl2s_b; signed long result; /* Initialize sl1s_a and sl2s_b */ result = sl1s_a / sl2s_b; |
Compliant Solution
This compliant solution tests the suspect division operation to guarantee there is no possibility of divide-by-zero errors or signed overflow:
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1s_a; signed long sl2s_b; signed long result; /* Initialize sl1s_a and sl2s_b */ if ( (sl2s_b == 0) || ( (sl1s_a == LONG_MIN) && (sl2s_b == -1) ) ) { /* Handle error condition */ } else { result = sl1s_a / sl2s_b; } |
Modulo
The modulo operator provides the remainder when two operands of integer type are divided.
...
This noncompliant code example can result in a divide-by-zero error during the modulo operation on the signed operands sl1
and sl2
s_a
and s_b
:
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1s_a; signed long sl2s_b; signed long result; /* Initialize sl1s_a and sl2s_b */ result = sl1s_a % sl2s_b; |
Compliant Solution
This compliant solution tests the suspect modulo operation to guarantee there is no possibility of a divide-by-zero error or an overflow error:
Code Block | ||||
---|---|---|---|---|
| ||||
signed long sl1s_a; signed long sl2s_b; signed long result; /* Initialize sl1s_a and sl2s_b */ if ( (sl2s_b == 0 ) || ( (sl1s_a == LONG_MIN) && (sl2s_b == -1) ) ) { /* Handle error condition */ } else { result = sl1s_a % sl2s_b; } |
Risk Assessment
A divide by zero can result in abnormal program termination and denial of service.
...