On Sat, 15 Sep 2012 16:06:38 +0200, Maxim Fomin <ma...@maxim-fomin.ru> wrote:

On Saturday, 15 September 2012 at 13:49:02 UTC, Simen Kjaeraas wrote:
void foo(ref S s); // cannot pass null pointer S* or null - "always there"

void bar( ref int n ) {
    n = 3;
}

void main( ) {
    int* p = null;
    bar( *p );
}

Good luck.

Of course, it's not that obvious in production code, but I've had this
happen to me in C++, and - obviously - it can happen in D, too.

The problem happens because you deliberately passed hidden null pointer.

In this very specific example, yes. In my case it happened because I
called a function with a vector of pointers to some class, some of which
were null, and that function did not expect nulls in the vector, passing
them on as references to null.


And in real code it could crash after dereferencing and before passing to bar, if accessed (meaning that problem is in erroneous pointer usage, not accepting ints through reference in bar). Certainly, it is possible to break even in such cases, as well as in other parts of the language which doesn't necessarily mean that such parts of the language are broken. What I was talking about is:

void bar( ref int n ) {
     n = 3;
}

void main( ) {
     int* p = null;
     bar(p); // error
     bar(null); //error
}

But that's like saying bar(int n) doesn't accept null as a parameter - of
course it doesn't - int and int* are different types.

What I'm saying is references may be a bit safer than pointers, but the
'guarantee' that they're not null pointers in disguise is a lie.

--
Simen

Reply via email to