Null references (oh no, not again!)

Walter Bright newshound1 at digitalmars.com
Wed Mar 4 10:12:32 PST 2009


bearophile wrote:
> I'm sure there are Safe-something classes for array bounds too, but
> they can't avoid most of the out-of-bound errors because very few
> people use it everywhere in programs, programmers are lazy.

I agree that people simply aren't going to use that class, for the 
reasons you mentioned.

> So I think a SafeInt class isn't much useful. Most or all C++
> programs I see around don't use it. Google code search lists 347
> usages of the word 'SafeInt' in C++ code: 
> http://www.google.com/codesearch?hl=en&sa=N&q=SafeInt++lang:c%2B%2B&ct=rr&cs_r=lang:c%2B%2B

I'm not in the least surprised how little penetration it has.


>> Or you could change the compiler to throw an exception on any
>> integer arithmetic overflow. Sounds great, right? Consider that
>> there's no hardware support for this, so the following would have
>> to happen:< This is going to slow things down and bloat up the code
>> generation. But wait, it gets worse. The x86 has a lot of complex
>> addressing modes that are used for fast addition, such as:< None of
>> these optimizations could be used if checking is desired.<
> 
> LLVM will have intrinsics to support such things. LDC may use them
> with a small amount of extra code in the front-end.

LLVM cannot change the underlying hardware, which does not easily 
support it.

> Some of those checks can be avoided, because sometimes you can infer
> the operation can't overflow.

I've done data flow analysis to try and prove such things - the cases 
you can avoid the checks are the small minority. You have to check even 
if you're just doing a ++. On the plus side, you rarely need an overflow 
check on pointer arithmetic if you've already got array bounds checking 
or assume things are in bounds.


> I have turned on such checks hundred of times in Pascal, TurboPascal,
> Delphi, and FreePascal programs, and it has allowed me to spot bugs
> that are far worse than some slowdown during debugging. I have
> written many times prototypes of programs in Python because it avoids
> such overflow bugs.
> 
> I like D also because it allows me to write fast programs, but for
> most programs most of the code isn't performance-critical, so lot of
> code isn't so damaged by such checks. That's why a large percentage
> of programs can today be written in managed languages or scripting
> languages or that are slower or way slower than good C/C++/D
> programs.
> 
> Note that such code bloat and slowdown can be limited to debug time
> only too, disabling such checks locally or globally in release
> versions, if the programmer wants so.

That's a good point.

Global switches are not appropriate for anything other than debugging, 
however, because some libraries may depend on overflow arithmetic.



More information about the Digitalmars-d mailing list