I recall a bug-report discussion that I sadly have never been able to find. It contains a pretty bad side-effect of this.
It had code like:
int *p;
// lots of code
if (p != NULL)
return 1;
// use p
Then a later refactor wrongly added a single line before the if statement: int *p;
// lots of code
int a = *p;
if (p != NULL)
return 1;
// use p
This meant the null check was optimized away, since de referencing a null pointer is undefined behavior, so the if-statement can be assumed to be always false.
This then lead to actual errors (perhaps even an exploit, I do not recall) arising from the removed null-check.I think in general the "sanity check" cases are the worst. It is hard to determine whether an expression causes undefined behavior if you cannot try and evaluate it. Perhaps a compiler intrinsic that checks (at runtime) whether an expression causes undefined behavior could be useful here. Though I can imagine such an intrinsic being essentially impossible to implement.