Skip to content

UB51⚓︎

Author: PeiHong Dai

Definition⚓︎

  • An object is assigned to an inexactly overlapping object or to an exactly overlapping object with incompatible type (6.5.16.1).
  • 将对象分配至与之不完全重叠或完全重叠的对象,且两者类型不兼容

Description⚓︎

  • If the value being stored in an object is read from another object that overlaps in any way the storage of the first object, then the overlap shall exactly match and the two objects shall have qualified or unqualified versions of a compatible type; otherwise, the behavior is undefined. (P91)

Code⚓︎

#include  <stdio.h>
long long longInt = 0x00007fffffffffff;
int main(void)
{
    char *src = ((char *) &longInt) + 5;
    printf("long:\t%lld\nchar:\t%d\n", longInt, *src);
}

Configurations⚓︎

OS: Microsoft Windows 11 22H2

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

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

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

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

Behaviors⚓︎

compilation successful
output:
long:   140737488355327
char:   127
compilation successful
output:
long:   140737488355327
char:   127

Advice⚓︎

  • Although no difference is spotted in this example, long long integer could be arranged at inverted ends, then a difference could appear.
  • To avoid this UB, programmers should avoid referencing part of an object memory if the arrangement is not explicitly and rigorously defined.