Should (p - q) be disallowed in @safe code?
Walter Bright
newshound2 at digitalmars.com
Thu Jan 1 21:53:00 UTC 2026
On 1/1/2026 12:47 PM, Timon Gehr wrote:
> 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.
That "can do whatever it wants" is a correct interpretation, but it would be
insane to deliberately set up a system that launched nuclear missiles upon
encountering UB.
I also object to common optimizations that interpret UB as license to delete the
offending code path.
> 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`.
The backends do not, to my knowledge, have any awareness of @safe or @system. I
don't see a scenario where not allowing p-q in @safe code would have any effect
on the backend.
> 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.
DMD's optimizer can detect null pointer dereferences as a result of copy
propagation, etc., and always gives a compile time error when it does.
Otherwise, it just dereferences the null pointer and whatever the CPU does with
it happens.
What the proposal in this thread is about is extending the @safe semantics to
not just be about memory safety, but about checking for common bugs where
rewriting the code slightly to avoid it is practical.
More information about the Digitalmars-d
mailing list