Hacker News new | ask | show | jobs
by chowells 2164 days ago
> meaning the compiler is not even obligated to keep it consistent from one build to another.

Way worse than that. The compiler wasn't obligated to act like anything at all. It would be totally legal to compile it so that the first time the value was accessed you got 0, the next time you got 1 - within the same program execution, with no mutation of the value. That is the sort of thing that is observed behavior of UB in the worst cases, and why it's so terrible to just pretend that UB is innocuous.

1 comments

Way worse than that, even. UB poisons every state of the program that eventually results in UB. For example, the optimizer is well within its rights to remove as dead code any branch that, if taken, would provably lead to UB at some arbitrary future point of execution.
That could literally produce no output program?
> That could literally produce no output program?

Way worse than even that (you might be noticing a theme here...). Once the optimizer has removed as dead code any branch that, if taken, would provably lead to UB at some arbitrary future point of execution, it can conclude that the other branch is now the only possible execution, and call it unconditionally, even if that leads to removing all your files (the classic example is https://kristerw.blogspot.com/2017/09/why-undefined-behavior...).

Yep! Dumb example.

    main()
      x = get_from_some_external_data_source()
      if x:
        print("Hello World")
        trigger_ub()
You might expect this code to always print if x is true but the optimizer can look at this and say "welp, if x is true then it would trigger ub, therefore it must be false, and since x must always be false we can just remove that entire branch."
My favorite example along these lines (in C) is "Cap'n'Proto remote vuln: pointer overflow check optimized away by compiler"[1] which was covered here a few years back and shows all of these "theoretical" compiler behaviors coming to a head in a real bug which is thoroughly explained.

1: https://news.ycombinator.com/item?id=14163111

c.f. “nasal demons”