6 ms·
Undefined behaviour has nothing to do with CPU architecture...
by aaaaaaaaaab 8y ago
Undefined behaviour has nothing to do with CPU architecture...
- woadwarrior01 8y agoIt is undefined in multithreaded scenarios, not in single threaded code. In a world where memory access latencies dominate and you pay a huge penalty for cache misses, and a smaller yet significant penalty for TLB misses, there are some significant performance gains that can be gained by tightly packing fields in structures, while still maintaining alignment at a structure level. We’ve been doing this safely for years in prod now. I understand that the dogma of “unaligned reads invoke undefined behavior” is rather popular given how memorable it is, but it isn’t always true.
- cesarb 8y agoIt's undefined even in single threaded code. The compiler can assume it's aligned and make optimizations which depend on it. It sounds like what you were doing is marking a struct as "packed", and accessing the fields directly (instead of through a pointer to the field). That should be fine.
- woadwarrior01 8y agoThis might be a bit too late to reply. It’s undefined in C, but it’s well defined at a processor level (on x86). IIRC, there was one particular bit of code that’d crash on AArch64 due to unaligned pointers, but would run a bit faster than aligned code on x86-64. On the other hand, this trick wouldn’t work in multithreaded code even if the semantics were well defined, due to false sharing of cache lines.