SHORT Re: Suggestion: "fix" assert(obj)

Don Clugston dac at nospam.com.au
Tue Jun 19 04:23:51 PDT 2007


Walter Bright wrote:
> Georg Wrede wrote:
>> Walter Bright wrote:
>>> Kristian Kilpi wrote:
>>>
>>>> The problem is that
>>>>
>>>>   assert(obj);
>>>>
>>>> does not first check if 'obj' is null.
>>>
>>>
>>> Yes it does, it's just that the hardware does the check, and gives 
>>> you a  seg fault exception if it is null.
>>
>> Asserts were INVENTED to *avoid segfaults*.
> 
> I don't know when assert first appeared. But I first encountered them in 
> the 80's, when the most popular machine for programming was the x86. The 
> x86 had no hardware protection. When you wrote through a NULL pointer, 
> you scrambled the operating systems, and all kinds of terrible, 
> unpredictable things ensued. Asserts were used a lot to try and head off 
> these problems.
> 
> Enter the 286. What a godsend it was to develop in protected mode, when 
> if you accessed a NULL pointer you got a seg fault instead of a 
> scrambled system. Nirvana! What was even better, was the debugger would 
> pop you right to where the problem was. It's not only asserts done in 
> hardware, it's asserts with:
> 
> 1) zero code size cost
> 2) zero runtime cost
> 3) they're there for every pointer dereference
> 4) they work with the debugger to let you know exactly where the problem is
> 
> Seg faults are not an evil thing, they're there to help you. In fact, 
> I'll often *deliberately* code them in so the debugger will pop up when 
> it hits them.

True, but forgetting to 'new' a class is an extremely common mistake. The first 
time I ever used classes in D, I didn't 'new' it (I bet this will happen to 
almost everyone from a C++ background!). Getting an AV with no line number is 
pretty off-putting. This remains the #1 situation where I use a debugger. And I 
hate using debuggers to find silly typos. Getting an assert failure with a line 
number would be enormously more productive.

BTW, the same 'it segfaults anyway' argument could be used to some extent for 
array bounds checking.



More information about the Digitalmars-d mailing list