5 ms·
> In the printf example, the compiler could trivially emit an error saying "NULL check on p after dereference of p" If you know that p is not NULL, the code is
by bnegreve 12y ago
> In the printf example, the compiler could trivially emit an error saying "NULL check on p after dereference of p"
If you know that p is not NULL, the code is just fine. The compiler has to compile it.
- infogulch 12y agoIf you know that p is not NULL then why are you checking for it? Either way, something is wrong here. Either you made a mistake with where you check for NULL, or you are performing extraneous operations for no reason.
- pcwalton 12y agoUsually this sort of thing comes up in code that's the result of several rounds of function inlining. Nobody would write that kind of code by hand, but it arises from the indirect results of several chains of function calls. In this regard, it's a very important optimization to be able to perform. Kent Dybvig's classic response to "Who writes that kind of code?" is "Macros do." Inlining has much the same effect as macros.
- infogulch 12y agoI can see how macros can throw a wrench into this, but couldn't compilers tell the difference between when someone wrote code that might have a bug and when it inlines a function that is a bit paranoid for that situation?
- pcwalton 12y agoYes, by allowing the optimizer the freedom to exploit undefined behavior, but coupling that with static analysis (or a stricter language semantics) that can catch bugs before they get to the optimizer.
- bnegreve 12y ago> If you know that p is not NULL then why are you checking for it? These dummy tests can happen if you have a lot of macros for example. It still valid C code as long as p is not NULL. A compiler generating an error on this particular example wouldn't be a correct C compiler. The compiler can reject this code if it can prove that p can be NULL, but in many case that's impossible at compile time. I agree that a warning would be nice though. edit: clarity.