from Hacker News

'Undefined behavior' doesn't exist

by leoncaet on 2/13/22, 1:38 PM with 3 comments

  • by Someone on 2/13/22, 3:12 PM

    > I have never seen even a single example of "undefined behavior" that I thought was justified. All "undefined behavior" that I have seen could have been replaced with "the compiler can do one of these three things" and still been widely efficient

    So, what’s that list for “write to a memory location outside allocated memory”?

    That may corrupt some internal structure for a hard-disk, causing a loss of the entire file system if data is later flushed.

    Worse, with memory-mapped I/O, that can trigger a change to an I/O pin, so it could conceivably launch an ICBM, starting world war three.

    The best one probably could do “it may or may not perform that write, and the write may have arbitrary effects, not necessarily immediately”. Is that truly better than “undefined behavior”?

  • by josephcsible on 2/13/22, 7:36 PM

    > All "undefined behavior" that I have seen could have been replaced with "the compiler can do one of these three things" and still been widely efficient

    The point of undefined behavior is that it's a list of things that the compiler is allowed to assume that you'll never do. A lot of optimizations come from being allowed to make this assumption and propagate it backwards, which can't be done at all if the compiler would have to do one of a defined list of things instead.

  • by tinalumfoil on 2/13/22, 1:48 PM

    > I have never seen even a single example of "undefined behavior" that I thought was justified

    That’s the whole point. The compiler doesn’t have to justify itself on undefined behavior.

    And no example that was justified? What about a compiler that turns dereferencing a null pointer into a memory access to address 0? Seems like a pretty reasonable translation to me.