Is D's pointer subtraction more permissive than C (and C++)?
Paul Backus
snarwin at gmail.com
Fri Apr 1 18:44:32 UTC 2022
On Friday, 1 April 2022 at 15:52:39 UTC, Ali Çehreli wrote:
> 1) Is D more permissive (or anemic in documentation:))? I ask
> because paragraph 5 below does not mention the pointers should
> be related in any way:
>
> https://dlang.org/spec/expression.html#pointer_arithmetic
The spec is permissive, but I would not be terribly surprised if
the implementation (specifically, LDC and GDC, which share
backends with C compilers) actually enforced the same
restrictions as C. There are similar issues with null
dereferences: D's spec says they have defined behavior, but
actual D compilers fail to guarantee this in some cases.
> 2) Is subtracting pointers that used to be in the same array
> legal.
>
> void main() {
> auto a = [ 1, 2 ];
> auto b = a;
> assert(a.ptr - b.ptr == 0); // i) Obviously legal?
>
> // Drop the first element
> a = a[1..$];
> assert(a.ptr - b.ptr == 1); // ii) GC-behaviorally legal?
>
> // Save the pointer
> const old_aPtr = a.ptr;
> // and move the array to another memory
> a.length = 1_000_000;
> // Expect a and b are on different blocks of memory
> assert(a.ptr != old_aPtr);
>
> assert(old_aPtr - b.ptr == 1); // iii) Practically legal?
> }
According to the C rules, (i) and (ii) are legal, since they
point to the same memory block, but (iii) is illegal.
More information about the Digitalmars-d
mailing list