On Friday, 13 June 2014 at 21:13:20 UTC, bearophile wrote:
This was surely discussed in past, but I don't remember the answer (so perhaps this is more fit in D.learn).

Dereferencing the null pointer in C is undefined behaviour, so in most cases the program segfaults, but sometimes the compiler assumes a dereferenced pointer can't be null, so it optimizes away tests and other parts, leading to bugs and problems, including exploits:

http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html

What's the solution for very optimizing D compilers like GDC, now and in future? Surely the C not-solution is not acceptable in a safe language as D.

Perhaps D can define dereferencing the null pointer in C as segfaulting in all cases. Is this acceptable for people that could desire to write a kernel in D?

An alternative possibility is to go the Java way, and add a compiler switch that adds an assert before every pointer dereference after the compiler has optimized the code (and remove some of such asserts where the compiler is certain they can't be null).

What's the solution used by Rust (beside not having to deal with nulls in many cases)?

Bye,
bearophile

Since you mentioned Java, NPE (NullPointerException) that throws every time null gets defererenced, is a real plaque of the language, hard to spot, hard to debug etc. So even without segfaults or exploits, nulls are PITA there and many programmers just refrain from using null values at all, explicitly initializing all references in 100% cases and marking all usages as @NotNull.

Maybe, if D decides to encourage programmers to use similar technique, it would be possible to optimize away most of such runtime checks and keep the language both fast *and* safe.

Reply via email to