What types have all valid bit patterns


#21

If the only UB is that the example prints any number, that’s different to it allowing remote code execution, for instance. But I guess that it’s best just to think of UB as a black box where anything (including the worst possible thing) can happen.


#22

Right, it should be considered a black box. It’s certainly interesting to see what happens in practice on a particular compiler version, but that’s mostly just intellectual curiosity.


#23

Just to make it clear, both C and Rust consider undefined behavior to be anything goes. The compiler is free to make literally anything happen including, but not at all limited to, segfaults.


#24

Although it’s been mentioned in many other threads, I haven’t seen it in this one. Some architectures, most notably Itanium, detect and fault on [edit: read] references to uninitialized memory. The fact that all bit patterns in an initialized memory cell are valid does not imply that the same memory cell can be read when uninitialized.


#25

It is best to think that. Sure, that specific toy program in the Playground might behave a particular way on a particular architecture, but what if the UB were part of a larger actively developed program? Who knows what might happen as code is added or removed or rearranged and the optimizer consequently gets a different view of the program.

And tbh even a black box approach isn’t sufficient. UB’s effects can potentially manifest anywhere in a program, not just at the site where the bad behavior is introduced.