Skip to content

UB16⚓︎

Author: PeiHong Dai

Definition⚓︎

  • Conversion to or from an integer type produces a value outside the range that can be represented (6.3.1.4).
  • 转换为整数类型或从整数类型转换产生超出可表示范围的值

Description⚓︎

  • 6.3.1.4 is about details of conversions between integer types and real floating types. Specifically, the two undefined situations are emphasized below:

  • When a finite value of standard floating type is converted to an integer type other than bool, the fractional part is discarded. If the value of the integral part cannot be represented by the integer type, the behavior is undefined.

  • When a value of integer type is converted to a standard floating type, If the value being converted is outside the range of values that can be represented, the behavior is undefined.

Code⚓︎

#include <stdio.h>
int main(void)
{
    double bigFloat = 9223372036854775807.0;
    int ovInt = bigFloat;
    printf("%d\n", ovInt);
}

Configurations⚓︎

OS: Microsoft Windows 11 22H2

gcc -v : gcc version 7.4.0, x86_64-w64-mingw32

compile and run commands: gcc -o UB16.exe UB16.c && ./UB16.exe
OS: Microsoft Windows 11 22H2

clang -v : clang version 6.0.0, x86_64-w64-mingw32

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

Behaviors⚓︎

compilation successful
output:
2147483647
compilation successful
output:
-240260744 (random numbers)

Advice⚓︎

  • This UB suggest that programmers should not risk to exert implicit type conversion on most types.
  • Better still, predefining a set of types that have strict boundaries and avoid conversions to the most extent could help.