3 ms·
> A program with undefined behavior is trivially not compliant with the specification. Undefined behavior means doing something the compiler spec does not spec
by kyllo 7y ago
> A program with undefined behavior is trivially not compliant with the specification.
Undefined behavior means doing something the compiler spec does not specify, therefore the compiler is free to do anything. There are plenty of programs that exploit the programmer's knowledge of a particular compiler's actual, unspecified behavior as an optimization.
One example is using an int variable after an overflow. Post-overflow, the int's value is undefined behavior, but in practice it is predictable for a given compiler and platform. It is possible to write a program that implements its own program spec correctly, while exploiting out-of-spec behavior of its compiler under the hood.
Much like how it's possible to wrap unsafe Rust code with a safe interface.
- fulafel 7y agoIt's worth noting that gcc and llvm treat C integer overflow as a can't-happen condition (unless you supply an explicit compiler flag to change overflow semantics).
- Too 7y agoRelying on undefined behavior because your compiler happens to behave a certain way today on one specific machine is NOT the same as wrapping unsafe with safe. Next version of the compiler can exploit the undefined behavior and simply remove the code as an optimization, or even worse the optimization is already in your current compiler and only happens under some strange circumstances you are not aware of. Unsafe code blocks still have defined and predictable behavior, but you have to guarantee the memory safety.
- saagarjha 7y ago> There are plenty of programs that exploit the programmer's knowledge of a particular compiler's actual, unspecified behavior as an optimization. And then they break when the compiler changes its behavior…
- likeliv 7y ago> There are plenty of programs that exploit the programmer's knowledge of a particular compiler's actual, unspecified behavior as an optimization. There are plenty of programs that have bugs. Programmers who exploit undefined behavior on purpose are reckless.