Should (p - q) be disallowed in @safe code?
Walter Bright
newshound2 at digitalmars.com
Sat Jan 3 00:00:31 UTC 2026
On 1/2/2026 2:54 PM, Timon Gehr wrote:
> On 1/2/26 22:03, Walter Bright wrote:
>> It seems we are in full agreement that p-q should be disallowed in @safe code,
>> which is my proposal here.
>> ...
>
> I am happy with each of these two outcomes:
> 1. `p-q` is `@safe`, implementation-defined.
> 2. `p-q` can be UB, must be `@system`.
>
> So, works for me.
>
>> BTW, p-q is not a memory safety issue.
>
> Any type of UB is a memory safety issue.
You are obviously correct. But using known computers, it is not a memory safety
measure. I don't see any reason anyone would implement p-q such that it trashes
memory or sets the CPU on fire. Maybe what actually happens should be
documented, to make it "implementation defined", but I'm not in a position to
authoritatively document what CPUs do.
Dereferencing random pointers, on the other hand, can realistically corrupt
memory. This is why pointer arithmetic is not allowed in @safe code.
> Any assumption that any type of UB is benign must rely on additional information
> about specific backends. So what you claim may be true with DMD, but that is
> about the extent of it.
I can't see a professionally designed CPU catching fire or corrupting memory by
subtracting two unrelated pointers. One would have to add more transistors to
make that happen. Nobody would buy such a machine.
Current CPUs are what they are. We live with that, and we trade off performance
for some level of unpredictable failure.
> I would expect a CPU to just do `i<<(j&31)`.
The X86_64 and Aarch64 give different results, I ran into that bug.
> The C abstract machine is however not the CPU.
CPU design has very much followed C semantics since the 80s. Unfortunately, the
C spec didn't nail down certain behaviors, and so we have different behaviors.
More information about the Digitalmars-d
mailing list