I'm pretty sure your snippet invokes nasal demons in all dialects. Dereferencing NULL is a pretty classic case where anything can happen once you do it. "Calling launch_missiles even though you don't want it to happen" is a subset of "anything," of course.
Consider what happens if you rearrange that example a bit, though. Let's say it's more like this:
int computation(int *ptr_a, int *ptr_b) {
if(ptr_a == NULL && ptr_b == NULL) return 0;
if(ptr_a == NULL) return val_b;
if(ptr_b == NULL) return val_a;
launch_missiles(); /* OK to put this here? */
return ...something with val_a and val_b...;
}
int otherComputation(int *ptr_a, int *ptr_b) {
int val_a = *ptr_a, val_b = *ptr_b;
int intermediate = computation(ptr_a, ptr_b);
return ...something with val_a, val_b, and intermediate....;
}
Then you call otherComputation in a tight loop. Should the compiler elide the NULL checks here, if computation gets inlined? otherComputation clearly requires that its parameters are non-NULL, so it should be fine to remove the checks. Failing to do so would be pretty annoying. It's clear that the inputs are constrained, and while you could fix it by factoring out the common code so that the NULL checks are explicitly optional, it would be best if the optimizer can handle it and not require us to rearrange our code to make it happy.That's really what I'm getting at. There are clear examples where it's bad to assume undefined behavior cannot happen and optimize away checks. But there are also clear examples where it's exactly what you want to do. Can the optimizer reliably distinguish between these cases?
I think the best answer is to have tools available like the undefined behavior sanitizer which can catch these problems at runtime. You want the optimizer to make your code as fast as it legally can. Trying to tone it down is going to be error-prone, and safety checks that can't be counted on are dangerous. You might end up just moving the problem around: instead of code suddenly being optimized out because the compiler proved it can't run without invoking undefined behavior, you'll have code suddenly being optimized out because something changed that made the compiler think you intended it. By checking at runtime, you recast the problem from "does the programmer intend to pass in values which will result in undefined behavior?" to "does this code actually get called with such values?" That's way easier to check, should have zero false positives, and should have as few false negatives with good test coverage.
I'm pretty sure your snippet invokes nasal demons in all dialects. Dereferencing NULL is a pretty classic case where anything can happen once you do it.
Is the dereferencing itself undefined in all dialects, or is it only undefined if one later "evaluates" the dereferenced value? Or do some define evaluation differently? For example (to my surprise) a comment by 'lkasndasd' on the corresponding Reddit thread points out that &* ptr is never undefined behavior in C, since the address operator and the dereference operator cancel out even (explicitly) if ptr is NULL:
6.5.3.2 Unary arithmetic operators, Semantics, paragraph 3:
The unary & operator yields the address of its operand.
[...] If the operand is the result of a unary * operator,
neither that operator nor the & operator is evaluated and
the result is as if both were omitted, except that the
constraints on the operators still apply and the result is
not an lvalue.
and footnote 102:
Thus, &*E is equivalent to E (even if E is a null pointer) [...]
https://www.reddit.com/r/programming/comments/3xk6zj/the_dan...I'm pretty sure the dereference is immediately UB (other than the case you quote here). Consider that when optimizations are off, that line will probably immediately execute a load instruction, generating a segfault.
nate@haswell:~/tmp$ cat deref.c
/* gcc -fno-inline -O3 -g -Wall deref.c -o deref */
/* (or as desired to show particular outcome) */
#include <stdio.h>
#include <stdlib.h>
void deref_and_print(int *ptr) {
int i = *ptr; /* undefined behavior if ptr is NULL */
if (ptr == NULL) printf("NULL\n");
else printf("%d\n", i);
}
int main(int argc, char **argv) {
int *ptr = NULL;
if (argc <= 1) {
printf("Usage: %s [arg]\n", argv[0]);
printf(" Demonstrates undefined behavior if 'arg'");
printf(" is not a positive integer\n");
exit(1);
}
int i = atoi(argv[1]);
if (i > 0) ptr = &i;
deref_and_print(ptr);
exit(0);
}
As you guessed, icc, gcc, and clang all crash with a segfault for 'deref 0' when compiled with -O0. But more interestingly, when compiled with -O1, -O2, or -O3, clang prints "NULL", while icc and gcc continue to crash.
Consider a programmer who feels it's clearer to dereference a and b once, rather than writing using * a and * b in the complicated math after the preliminary checks. And because they don't want to rely on C99 or distract by opening a new block, they put the conversion at the top of the function. Oh, and the new guy decided to add the "missile launch" code here.
I think there is a reasonable argument that there is a difference between optimizing when a code path can be shown to never occur because of constrained inputs, and optimizing because behavior supposedly can be inferred from the absence of undefined behavior.I'm fine with a literalist compiler that produces code that crashes when it immediately tries to dereference a NULL pointer, with one that produces code that does the safety checks but defers the load, but even if allowed by the spec[1] I don't think it's good behavior for a compiler to silently omit the safety checks and launch the missiles when passed a NULL.
[1] Is this undefined behavior according to the spec? I consider myself an expert C programmer, and I think it's undefined in C99, but I wouldn't bet that I've correctly understood the issues for the other dialects of C, muchless C++. Is a conforming compiler "allowed" to skip the safety checks and launch the missiles? I don't know, and thus defensively wouldn't write the code like this, but it would be nice to think that long-standing mission-critical code written by others won't suddenly stop working with a new release of the optimizing compiler.