Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Assume p is a pointer. Then this is possibly invoking undefined behavior, unless the compiler can prove that p will never be NULL:

  *p;


Then you require that either the programmer checks if the pointer is null, or the compiler can infer that it isn’t null, or that you add an annotation for that. (Either an annotation for a method parameter to require it not to be null, or an annotation that marks it as nullable, or an annotation that disables these warnings.

It’s what we do in Java, too.


The real problem is when compilers make assumptions based on such uses. For example, optimizing C compilers will see that, and assume that p must not be NULL, because otherwise it would be undefined. That can lead to dangerous results. John Regehr is a computer science professor at the University of Utah, and has written about this extensively: http://blog.regehr.org/archives/213


This optimization exists for a reason. With macros, operator overloading or templates it's very easy to generate code like this:

  if (!p) { return -1; } else { do something; }
  if (!p) { return -1; } else { do something else; }
  if (!p) { return -1; } else { do even more; }
  ...
And now, you want the compiler to remove all these redundant checks.

Moreover, you very likely don't want warnings here.


If you look at the comment history, you'll find I have recently argued why you don't want warnings for these kinds of things. But I agree with Regehr et al.'s proposal for a Friendly C, http://blog.regehr.org/archives/1180, which would disallow optimizing way those null-pointer checks. Any attempt for myself to justify why would just restate, poorly, what Regehr and company already state in that post and the ones linked to from it.

I think it's worth noting that some critical code, such as the Linux kernel, already opts out of such optimizations because they've been bitten by it in the past. My previous post talks about that.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: