Should (p - q) be disallowed in @safe code?
Nick Treleaven
nick at geany.org
Sat Jan 3 14:35:53 UTC 2026
On Friday, 2 January 2026 at 02:00:29 UTC, Timon Gehr wrote:
> a) There does not actually seem to be any explicit
> documentation in the D spec about pointer subtraction. If there
> is, I have not found it.
Point 6 here:
https://dlang.org/spec/expression.html#pointer_arithmetic
> If both operands are pointers, and the operator is -, the
> pointers are subtracted and the result is divided by the size
> of the type pointed to by the operands.
It sounds like we need to put in an undefined behaviour note.
What about *RelExpression* on pointers, UB or not?
> b) In some popular languages, `p-q` is UB if `p` and `q` point
> to different memory objects.
>
> c) It's hence possible that some D backends give UB to this
> expression when according to your intention they should not.
>
> d) This scenario is not implausible, I think it already happens
> for null pointer dereferences that code that the frontend says
> is `@safe` is treated as UB by some of the backends.
Yes as of May, that requirement is in the spec:
https://dlang.org/spec/function.html#null-dereferences
More information about the Digitalmars-d
mailing list