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

Timon Gehr timon.gehr at gmx.ch
Thu Jan 1 20:47:12 UTC 2026


On 1/1/26 18:18, Walter Bright wrote:
> On 1/1/2026 7:18 AM, Timon Gehr wrote:
>> In C, subtracting pointers to different memory objects is undefined 
>> behavior, hence side-effecting.
>>
>> Subtracting pointers can be `@safe` iff it is always defined behavior. 
>> (Even if the defined behavior is to yield a nonsense value.)
> 
> Getting a nonsense value is memory safe, but is almost certainly a bug.
> ...

Well, that was the point. Vladimir had said that pointer subtraction is 
free of side effects, but UB would *be* the side effect. And AFAIU 
according to the C standard it can be UB. This does not merely mean that 
the result could be nonsensical (which, for the record, would *not* be a 
bug in C), it means the program can do whatever it wants.

As long as it is defined behavior in D, keeping it `@safe` is perfectly 
fine. But differences to C and C++ may nevertheless trip up some 
implementations and violate memory safety, as backends were developed 
with C and C++ in mind.

`@safe` has to be consistent with the backend semantics. This means 
either making certain constructs `@system` or ensuring all backends 
compile them safely, or having a broken `@safe`.

> 
>> I am not sure how GDC and LDC are currently treating this.
> 
> Since the same front end is used, I'd be surprised if they behaved 
> differently.

UB is mostly a glue/backend thing, it's about what the code *means*, not 
about how it is type checked by the frontend. And backends are often 
biased towards C and C++ semantics.

There are other cases, e.g., with DMD a null dereference may be a 
guaranteed segfault, but I think it's likely UB with GDC and LDC.

It seems LDC even has the flag `-fno-delete-null-pointer-checks` to turn 
off UB on null pointer dereference, which would indeed indicate it is UB 
by default.


More information about the Digitalmars-d mailing list