www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Are null refs intentionally allowed?

reply Dukc <ajieskola gmail.com> writes:
This compiles and runs just fine, printing what you'd except:

```D
 safe void main()
{
     import std.stdio;

     int* p;
     isNull(*p).writeln;
     p = new int(5);
     isNull(*p).writeln;
}

 safe bool isNull(ref int x){return &x is null;}
```

The question is, is this intentional? I'm writing "DIP1000: 
Memory Safety in a Modern System Programming Language Pt. 2" and 
currently I've written that this is allowed, even when it's not 
in C++.

But there are still two possibilities: either this is okay by 
design, or works by accident but really disallowed. Which is the 
case?
Jul 16 2022
next sibling parent reply Tejas <notrealemail gmail.com> writes:
On Saturday, 16 July 2022 at 12:33:57 UTC, Dukc wrote:
 This compiles and runs just fine, printing what you'd except:

 ```D
  safe void main()
 {
     import std.stdio;

     int* p;
     isNull(*p).writeln;
     p = new int(5);
     isNull(*p).writeln;
 }

  safe bool isNull(ref int x){return &x is null;}
 ```

 The question is, is this intentional? I'm writing "DIP1000: 
 Memory Safety in a Modern System Programming Language Pt. 2" 
 and currently I've written that this is allowed, even when it's 
 not in C++.

 But there are still two possibilities: either this is okay by 
 design, or works by accident but really disallowed. Which is 
 the case?
It doens't compile when I run it on run.dlang.io, erroring out with: ``` onlineapp.d(11): Error: cannot take address of parameter `x` in ` safe` function `isNull` ```
Jul 16 2022
parent Dukc <ajieskola gmail.com> writes:
On Saturday, 16 July 2022 at 12:40:06 UTC, Tejas wrote:
 It doens't compile when I run it on run.dlang.io, erroring out 
 with:
 ```
 onlineapp.d(11): Error: cannot take address of parameter `x` in 
 ` safe` function `isNull`
 ```
Oh sorry, it needs `-preview=dip1000`
Jul 16 2022
prev sibling parent Paul Backus <snarwin gmail.com> writes:
On Saturday, 16 July 2022 at 12:33:57 UTC, Dukc wrote:
 This compiles and runs just fine, printing what you'd except:

 ```D
  safe void main()
 {
     import std.stdio;

     int* p;
     isNull(*p).writeln;
     p = new int(5);
     isNull(*p).writeln;
 }

  safe bool isNull(ref int x){return &x is null;}
 ```

 The question is, is this intentional? I'm writing "DIP1000: 
 Memory Safety in a Modern System Programming Language Pt. 2" 
 and currently I've written that this is allowed, even when it's 
 not in C++.
In general, dereferencing `null` has defined behavior and is allowed in ` safe` code. So I think this example is fine.
Jul 16 2022