Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: got rid of absolute value example and overflow UB

Division and modulo operations are susceptible to divide-by-zero errors. 

The C Standard identifies two conditions the following condition under which division and modulo remainder operations result in undefined behavior (UB):

If the quotient a/b is not representable, . . . the behavior of both a/b and a%b is undefined (6.5.5)
UBDescription

45

The value of the second operand of the / or % operator is zero (6.5.5).

n/a

Ensure that division and remainder operations do not result in divide-by-zero errors.

Division

The result of the / operator is the quotient from the division of the first arithmetic operand by the second arithmetic operand. Division operations are susceptible to divide-by-zero errors. Overflow can also occur during two's complement signed integer division when the dividend is equal to the minimum (negative) value for the signed integer type and the divisor is equal to −1. (See INT32-C. Ensure that operations on signed integers do not result in overflow.)

...

Code Block
bgColor#ccccff
langc
#include <limits.h>
 
void func(signed long s_a, signed long s_b) {
  signed long result;
  if ((s_b == 0 ) || ((s_a == LONG_MIN) && (s_b == -1))) {
    /* Handle error */
  } else {
    result = s_a % s_b;
  }
  
  /* ... */
}

Compliant Solution (Absolute Value)

The division and remainder operators truncate toward 0, as specified in subclause 6.5.5, footnote 105, of the C Standard [ISO/IEC 9899:2011], which guarantees that

Code Block
i % j

and

Code Block
i % -j

are always equivalent.

However, the minimum signed value remainder −1 results in undefined behavior because the minimum signed value divided by -1 is not representable.

Code Block
bgColor#ccccff
langc
#include <limits.h>
 
void func(signed long s_a, signed long s_b) {
  signed long result;
  if (s_b == 0 || (s_a == LONG_MIN && s_b == -1)) {
    /* Handle error */
  } else {
    if ((s_b < 0) && (s_b != LONG_MIN)) {
      s_b = -s_b;
    }
    result = s_a % s_b;
  }

  /* ... */
}

Risk Assessment

...