Should (p - q) be disallowed in @safe code?

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Sat Jan 3 00:38:51 UTC 2026


On 03/01/2026 9:21 AM, Walter Bright wrote:
> On 1/2/2026 11:20 AM, jmh530 wrote:
>> On Thursday, 1 January 2026 at 06:15:09 UTC, Walter Bright wrote:
>>> [snip]
>>> So this would be valid, as the two pointers are known to point to the 
>>> same memory object.
>>> [snip]
>>
>> To what extent can D know when pointers are known to point to the same 
>> object?
> 
> Some can be done trivially, such as (&c - &d). More can be discovered 
> with DFA (Data Flow Analysis), but not really that much. Just like not 
> many cases of null dereference can be unambiguously discovered with DFA.

Four days ago I started implementing value tracking.

I can get objects like:

```d
int a, b;
int* ptr = condition ? &a : &b;
```

And see that ptr could be either a or b.

Its also possible to see:

```d
int* ptr = new int, oldObj = ptr;

foreach(i; 0 .. 10) {
	ptr = new int;
}

assert(ptr !is oldObj);
```

But what you can't do with DFA alone:

```d
void func(int* a, int* b) {
	assert(a is b); // how can I know this?
}
```

While I'd love to have knowledge that pointers are not from the same 
object, or are, realistically its beyond what can be annotated on code 
explicitly, let alone inferred.

I've been trying to solve for this for well over a year and have not 
made progress on it.

The best you can really hope for here I suspect is ownership transfer 
and modelling it in the function that borrows from it. As well as new 
and stack allocations ext.


More information about the Digitalmars-d mailing list