In the most interesting cases, it can't reasonably be detected at compile-time anyway.
See also here:
http://blog.llvm.org/2011/05/what-every-c-programmer-should-...
The problem, as Regehr (the author of this submission) has pointed out many times before, is more subtle than that. Because certain behavior is considered undefined, compilers are allowed to assume the code it is compiling is well defined, and optimize accordingly. That can cause simple bugs to have mysterious effects. For example:
a->thing = 42;
if (a == NULL) {
return;
}
Obviously that code is wrong; I should check for NULL before using a. But because I dereferenced a, the compiler can assume a must not be NULL, and just removes the null check as dead code. This scenario has caused problems in the kernel, and made bad bugs even worse.But the compiler could just as well emit a warning "useless NULL comparison" instead of blithely assuming that the programmer intentionally wrote a book expression. That wouldn't handle every case of UB, but would handle many.
Re:The Problem with Friendly C
by superuser2 on Thursday December 24, 2015 @01:45AM
(#10787369)
A warning on removed dead code isn't helpful because dead come is legitimately removed all the time. No one would ever heed it.
If you ignored dead code produced by macros and limited the check to function-scope, I think you'd mostly eliminate false positives.
Re:The Problem with Friendly C
by daurnimator on Wednesday December 23, 2015 @09:42PM
(#10786785)
It's usually only at runtime rather than compile time that such situations arise.
At runtime we have the clang and gcc undefined behaviour sanitizers, but they aren't free in terms of performance.
Then again, I think languages shouldn't have undefined behaviour and that programmers who use languages with undefined behaviour deserve what they get.