this is null

Paul Backus snarwin at gmail.com
Sat Mar 9 20:04:53 UTC 2019


On Saturday, 9 March 2019 at 19:18:38 UTC, ANtlord wrote:
> Hello everyone! I've encountered the problem which I already 
> encountered before. Unfortunately, I had no time in the 
> previous time to report and to talk about it. So I decided to 
> play making my own "malloc" function in pure D (betterC) at 
> this time. And I encountered the issue one more time. `this` 
> can be null. How? Please take a look at my project [0]. It gets 
> the current heap break and tries to increase via a free list. 
> So the segfault I meet happens there [1]. Tell me, please. What 
> do I wrong?
>
> [0] https://github.com/ANtlord/deadmemory
> [1] 
> https://github.com/ANtlord/deadmemory/blob/master/src/deadmemory/freelist.d#L56

You can end up with a null `this` reference if you dereference a 
null pointer to a struct and then call a method on the result. 
For example:

struct S
{
     bool isThisNull() { return &this is null; }
}

void main()
{
     import.std.stdio;
     S* p = null;
     writeln((*p).isThisNull); // true
}

Interactive version: https://run.dlang.io/is/fgT2rS


More information about the Digitalmars-d-learn mailing list