UB42⚓︎
Author: Yikai Cui.
Definition⚓︎
If the quotient a/b is not representable, the behavior of both a/b and a%b (6.5.5).
a/b 的商不能表示时,a/b 和 a%b 的行为。
Description⚓︎
If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined.
如果商 a/b 可以表示,表达式 (a/b)*b + a%b 的值应该等于 a;否则,a/b 和 a%b 的行为是未定义的。
Code⚓︎
#include <stdio.h>
#include <limits.h>
int main() {
int a = INT_MIN;
int b = -1;
printf("%d\n", a);
int c = a / b; // Undefined behavior! (1)
printf("%d", c);
}
- Undefined behavior! The quotient
a/bis actuallyINT_MAX + 1, which is not representable, whatever valueINT_MINis.
Configurations⚓︎
OS: Microsoft Windows 11 22H2
gcc -v : gcc version 11.2.0 (GCC), x86_64-w64-mingw32
compile and run commands: gcc UB42.c -o UB42.exe && ./UB42.exe
OS and cl.exe version: same as UB21.1.c MSVC
compile and run commands: cl.exe /FeUB21.2 UB21.2.c && ./UB21.2.exe
Behaviors⚓︎
- Compilation successful.
- Runtime: program halts (but not terminate) before printing
c.
- Compilation successful.
- Runtime: program terminates before printing
cwith return code 0xC0000095. (It is a special status code in Windows indicating aSTATUS_INTEGER_OVERFLOWhas happened. Refer to the specifacation on Microsoft's website.)
Advice⚓︎
Programmer should be quite aware of the possible value of the devision oprands during coding, which is often neglected. For example, if any of the oprand comes from user input, in order to avoid this undefined behavior which would result in unexpected exceptions or infinite loops (like the behavior in MinGW), it is necessary to check and make the assertion of the value before using it.