Is undefined behavior only an issue if you are deploying on several platforms?

前端 未结 12 955
谎友^
谎友^ 2020-12-24 10:47

Most of the conversations around undefined behavior (UB) talk about how there are some platforms that can do this, or some compilers do that.

What i

12条回答
  •  -上瘾入骨i
    2020-12-24 11:10

    Nothing is changing but the code, and the UB is not implementation-defined.

    Changing the code is sufficient to trigger different behavior from the optimizer with respect to undefined behavior and so code that may have worked can easily break due to seemingly minor changes that expose more optimization opportunities. For example a change that allows a function to be inlined, this is covered well in What Every C Programmer Should Know About Undefined Behavior #2/3 which says:

    While this is intentionally a simple and contrived example, this sort of thing happens all the time with inlining: inlining a function often exposes a number of secondary optimization opportunities. This means that if the optimizer decides to inline a function, a variety of local optimizations can kick in, which change the behavior of the code. This is both perfectly valid according to the standard, and important for performance in practice.

    Compiler vendors have become very aggressive with optimizations around undefined behavior and upgrades can expose previously unexploited code:

    The important and scary thing to realize is that just about any optimization based on undefined behavior can start being triggered on buggy code at any time in the future. Inlining, loop unrolling, memory promotion and other optimizations will keep getting better, and a significant part of their reason for existing is to expose secondary optimizations like the ones above.

提交回复
热议问题