Skip to content

UB41⚓︎

Author: Yikai Cui.

Definition⚓︎

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

除法或取模运算的第二操作数为零时。

Description⚓︎

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined. (from ISO/IEC 9899:2023(E) 6.5.5, 6)

除法运算的结果是首个操作数除以第二个操作数的商;取模运算的结果是其余数。在两种运算中,如果第二个操作数是0,行为是未定义的。

Code⚓︎

UB41.c
#include<stdio.h>

int div(int x, int y) {
    return x / y;       // Undefined behavior! (1)
}

int main() {
    int x = 10;
    int y = 0;
    printf("%d", div(x, y));
}
  1. Undefined behavior! Here compiler do not know the values of x and y. If y == 0, the behavior is undefined.

View source

Configurations⚓︎

OS: Microsoft Windows 11 22H2

gcc -v : gcc version 11.2.0 (GCC), x86_64-w64-mingw32

compile and run commands: gcc UB41.c -o UB41.exe && ./UB41.exe

OS: Ubuntu 20.04 x86_64 GNU/Linux

clang -v : 17.0.0, Target: x86_64-pc-linux-gnu

compile and run commands: clang UB41.c -o UB41.exe && ./UB41.exe

Behaviors⚓︎

  • Compilation successful
  • Output: None (Runtime Error!)
  • Return code: 0xC0000094. (It is a special status code in Windows named STATUS_INTEGER_DIVIDE_BY_ZERO, indicating that an integer is divided by zero. Refer to the specifacation on Microsoft's website.)
  • Compilation successful
  • Output: Floating point exception (core dumped)
  • Return code: 136. (It is a user-defined exit code in clang, indicating that a program was aborted, receiving SIGFPE)

Advice⚓︎

Division by zero is one of the most frequent undefined behaviors. And as in the code above, if the second oprand is based on user input or function parameter, the compiler cannot determine whether the second oprand is zero during compilation.

So the responsibility of checking whether second oprand is zero is on the programmer. If it cannot be assured that div by zero error would not occur, then it is necessary to check it.