Disallow null references in safe code?
Jonathan M Davis
jmdavisProg at gmx.com
Mon Feb 3 14:18:10 PST 2014
On Monday, February 03, 2014 09:30:32 Ary Borenszweig wrote:
> On 2/1/14, 7:14 AM, Jonathan M Davis wrote:
> > In the general case, you can only catch it at compile time if you disallow
> > it completely, which is unnecessarily restrictive. Sure, some basic cases
> > can be caught, but unless the code where the pointer/reference is defined
> > is right next to the code where it's dereferenced, there's no way for the
> > compiler to have any clue whether it's null or not.
>
> This is not true. It's possible to do this, at least for the case where
> you dereference a variable or an object's field. See this:
>
> http://crystal-lang.org/2013/07/13/null-pointer-exception.html
In the _general_ case it is not possible. It's certainly possible within
certain snippets of code - any obvious example being
int* i;
*i = 5;
but it's not possible for the compiler to know under all sets of
circumstances. Something as simple as using a function's return value makes it
so that it can't know. e.g.
int* i = foo();
*i = 5;
For it to know, it would have to examine the body of foo (which it doesn't
necessarily have the code for under C's compilation model - which D uses), and
even if it did that wouldn't be enough e.g.
int* foo()
{
return "/etc/foo".exists ? new int : null;
}
The compiler could flag that as _possibly_ returning null and therefore the
previous code _possibly_ dereferencing null, but it can't know for sure.
So, with full program analysis, it would certainly be possible to determine
whether a particular pointer _might_ be null when it's dereferenced and flag
that as a warning or error, but without full program analysis (which the
compiler can't normally do with C's compilation model), you can't do that in
most cases, and even with full program analysis, you can't always determine
whether a pointer will definitively be null or not when it's dereferenced.
Crystal's compilation model may allow it to check a lot more code than C's
does, allowing it to detect null dereferences in more cases, and it may very
well simply error out when it detects that a pointer _might_ be null when
it's dereferenced, but as I understand it, it's fundamentally impossible to
determine at compile time under all circumstances whether a pointer will
definitively be null or not (as evidenced by the body of foo above - the
result depends entirely on runtime state).
- Jonathan M Davis
More information about the Digitalmars-d
mailing list