Re:Falsehoods programmers believe about undefined behavior
by account42 on Monday November 28, 2022 @10:11AM
(#33774557)
Sad to see this downvoted here.
To hammer it in, the consider the following:
if(p) *p = 0;
*p is undefined if p is NULL. But as long as that statement is never reached when p is NULL that is not a problem. That is trivially true in this case, but the same applies even for more complex relations between the conditional and the undefinedness of the statement.
Or put another way, in
int * p = 0;
if(fermats_last_theorem_is_wrong()) {
p = malloc(sizeof(int));
*p = 0;
}
if(p) {
puts("fermats last theorem is wrong\n");
}
if(fermats_last_theorem_is_wrong()) {
*p == 1;
}
if(p) {
puts("fermats last theorem is wrong\n");
}
the compiler is not allowed to remove the if(p) checks and unconditionally print that fermats last theorem is wrong unless it can prove that fermats_last_theorem_is_wrong() is true.In fact, something having undefined behavior and the compiler being allowed to assume that it is unreachable are effectively the same thing. Which is why the spec for std::unreachable() and the compiler-specific intrinsics that preceded it is that it invokes undefined behavior and not more complex wording.
Re:Falsehoods programmers believe about undefined behavior
by tsimionescu on Tuesday November 29, 2022 @03:33AM
(#33785053)
Yes, my example with Fermat's last theorem was completely wrong, not sure why it seemed plausible to me when I wrote it, it's obviously just a guard, and it obviously is not UB to have a pointer write behind an If...
> Furthermore, if every possible execution of a given program would result in undefined behavior, the given program is not strictly conforming. A conforming implementation must not fail to translate a strictly conforming program simply because some possible execution of that program would result in undefined behavior. Because foo might never be called, the example given must be successfully translated by a conforming implementation.