#include <stdio.h>
int main(){
int a = -1;
int b = -1;
long c = *(long*)&b; // expect `c` to also be -1.
// assuming `int` is 4 bytes and `long` is 8 bytes.
return 0;
}
Does the above code produce undefined behaviour according to the strict aliasing rule?: What is the strict aliasing rule?
Above code runs fine even with compiler optimization on.
I have even used the -fsanitize="undefined"
option of gcc
but still got no errors at runtime.
Why will the above code cause UB? and how else can I accomplish such thing? is using memcpy
and copying the memory content the only option?