[dmd-internals] Asserts

Walter Bright walter at digitalmars.com
Fri Nov 9 00:33:53 PST 2012


On 11/8/2012 11:40 PM, David Held wrote:
> My personal policy is to assert early and assert often.  I see many functions 
> taking pointer args and dereferencing them without checking for NULL first.  I 
> know Walter likes to claim that dmd doesn't have any NPEs because he is a 
> careful coder;

Not exactly. My argument is that the assert:

void test(T* p) {
     assert(p != null);
     ... *p ...
}

is redundant because the hardware will do that for you. Compile with debug on, 
run it under the debugger, and you'll get the file/line plus a lovely stack trace.

This works so well I'll often insert:

    *cast(char*)0=0;

into code just to see how it got there.

> but the fact is, he is not the only coder, and most functions don't explicitly 
> document which arguments are allowed to be NULL and/or when.  Of course, it 
> would be better for non-null arguments to just pass by reference, but fixing 
> that would be quite disruptive in most cases (and outright infeasible in 
> others, like void*).

Unfortunately, references can also be null pointers.

>
> However, I also know that asserting in every function is a religious issue for 
> some, so I thought I would ask the dev community about thoughts on this topic.

I like using asserts for non-obvious checks for logic errors, such as what I 
call loop-back tests. For example, calculating the number of bytes that will be 
written, and then at the end verifying that the number of bytes written matches. 
Those kinds of asserts detect loads of bugs.

Having a null pointer in the wrong spot is just another bug, I don't really 
understand all the press it gets. It's not even a particularly bad one, as it 
won't result in silently corrupted data. I find array overflows and 
uninitialized data to be far, far, far worse in terms of consuming my time. But 
fortunately, valgrind has ridden to the rescue there and has saved me enormous 
effort. So again, I tend not to focus on using asserts for those issues. In my 
not-so-humble (and probably unique) opinion, valgrind has kept C (and maybe even 
C++) off of the ash heap of history.


More information about the dmd-internals mailing list