I expected this to print 11112222deadbeef (it does at -O0), but at -O3 it prints 1111222233334444.
https://godbolt.org/z/MfeEM8fqP
#include <stdint.h>
#include <stdio.h>
__attribute__((noinline))
void MyFun(void *p)
{
*(uint32_t*)p = 0xDEADBEEF;
}
int main(void){
uint64_t x = 0x1111222233334444ULL;
MyFun(&x);
printf("%016llx\n", (unsigned long long)x);
}
Searching found a compiler option -fno-strict-aliasing which basically states:
With -fno-strict-aliasing, you are advising the compiler that you might have written some incorrect code, and to please be defensive with the optimizations it performs regarding aliasing.
Applying that option -O3 -fno-strict-aliasing does output the expected result 11112222deadbeef. Example
What's the correct, portable way to write 0xDEADBEEF into the low-addressed 4 bytes of a uint64_t so it does not get optimized away or is it safe to add -fno-strict-aliasing as a temporary stop-gap?
memcpy().printf( "%016llx\n", ( unsigned long long )x ), you can useprintf( "%016" PRIx64 "\n", x );. No casting. You need to includeinttypes.h, but you can omitstdint.hif you do.