Inconsistent Output on Different Optimization Levels for Uninitialized Structure Member Reference
When compiling this code using Clang++ with the -O0 optimization level, the program executes successfully(see https://godbolt.org/z/6G4evhKE1). However, when using optimization levels -O1, -O2, or -O3, the program consistently returns an error code of 200(see https://godbolt.org/z/x9dzrd75j). I am seeking clarification on whether this behavior can be considered a bug or a deliberate design choice.
Version
clang version 19.0.0git (https://github.com/llvm/llvm-project.git 987087df90026605fc8d03ebda5a1cd31b71e609)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /home/cTest/llvm-project/mybuild/bin
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Candidate multilib: .;@m64
Selected multilib: .;@m64
Command
clang++ -fsanitize=undefined -O2 bug.c
Code
cat bug.c
struct S {
int a;
};
int main() {
struct S s;
struct S *p = &s;
return p->a;
}
clang++ -fsanitize=undefined -O2 bug.c
You should use msan: https://godbolt.org/z/eq55eMdsG. Loading an uninitialized variable is UB.
Using an indeterminate value is indeed undefined behavior. The optimizer will always assume that a program is well-defined and make choices accordingly. We can see form the IR: https://godbolt.org/z/fcEb9Kehn
That the value becomes undef:
ret i32 undef
So all bets are off at this point. This is a bug in your program.
Thank you for your responses. I will consider the UB filtering issue in the upcoming testing process.