flagging runtime null dereferencing

Steven Schveighoffer schveiguy at yahoo.com
Fri Nov 14 14:36:49 PST 2008


I know this has been brought up many times, but I think possibly the 
usefulness of this feature has been underestimated, and its cost 
overestimated.

Consider several points:

1. check for null needs to be done only when the source of the variable is 
unknown.
2. segfaults can come from other sources, esp. memory corruption.  It is 
useful to distinguish null dereference (which is almost always an 'I forgot 
to initialize' error).
3. check for null can easily be removed during release mode, especially if 
it translates directly into an assert.
4. Yes, segfault is a loud error, but it's like hearing a gunshot from under 
water.  It's loud, but you have no idea where it's coming from, or whether a 
null dereference is to blame.  An assert is much more useful because it 
tells you the line of code that fails.  And please *please* don't tell me to 
create a core dump, or use Dr. Watson.  Not helpful.

I again propose that the D compiler in non-release mode inserts assert null 
checks where it can't prove that a pointer being dereferenced is not null, 
and removes those checks in release mode.

Example of "where it can't prove":
class C { void method();}
void fn(C c)
{
   c.method(); // can't prove c is not null, insert check
   c.method(); // know c is not null because it was checked above
}

In addition, I'd propose that the compiler does a static check to see if a 
null dereference definitely will happen.  e.g:

C c;
c.method(); // should be a compile error.

Ran into this again, and again, had to spend too much time finding it.

-Steve 





More information about the Digitalmars-d mailing list