Skip to content

UB14⚓︎

Author: PeiHong Dai

Definition⚓︎

  • Two declarations of the same object or function specify types that are not compatible (6.2.7).
  • 同一对象或函数的两个声明的指定类型不兼容

Description⚓︎

  • Two types are compatible types if they are the same.
  • Additional rules for determining whether two types are compatible are described in 6.7.2 for type specifiers, in 6.7.3 for type qualifiers, and in 6.7.6 for declarators. For structure, union and enumerating types, check out 6.2.7 and ^59)^ for more details.
  • All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

Code⚓︎

char a = 'a';
int try() {
    return 0;
}
#include <stdio.h>
extern int a[10];
int main() {
    printf("%d\n", a[6]);
    return 0;
}

Configurations⚓︎

OS: Microsoft Windows 11 22H2

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

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

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

compile and run commands: clang -o UB14.exe UB14.1.c UB14.2.c && ./UB14.exe

Behaviors⚓︎

Compilation successful
Compilation successful

Advice⚓︎

  • This UB is very counter-intuitive since contradictions in type usually causes error.
  • However, ELF file does NOT keep track of variable type, making such situations acceptable for main stream compilers
  • Programmers are advised to use identical types while referring to the same object in the same scope.
  • For external variables, try not to contradict to the previous definition so as to avoid confusions.
  • Mainstream IDEs provide static code analysis tools that are able to discover faulty codes. If IDE warns, double check to confirm.