www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - =?UTF-8?B?wqc=?= 28.3 Pointers and the Garbage Collector

reply kdevel <kdevel vogtner.de> writes:
In § 28.3 Pointers and the Garbage Collector [1] we read

    Do not add or subtract an offset to a pointer such that the 
result points
    outside of the bounds of the garbage collected object 
originally allocated.

       char* p = new char[10];
       char* q = p + 6; // ok
       q = p + 11;      // error: undefined behavior
       q = p - 1;       // error: undefined behavior

C and C++ allow a pointer to point to the (non-existing) element 
after the end
of the array:

    char *e = p + 10;

Does this point "outside of the bounds of the garbage collected 
object"?

In § 28.3 we also read

    Do not depend on the ordering of pointers:

       if (p1 < p2)  // error: undefined behavior
          ...

    since, again, the garbage collector can move objects around in 
memory.

In C and C++ we are used to read code like this:

    void foo ()
    {
       char *p = new char [10];
       char *e = p + 10;
       char *q;
       for (q = p; q < e; ++q)
          ...
    }

Does this for-loop "depend on the ordering of pointers"?

[1] https://dlang.org/spec/garbage.html#pointers_and_gc
Apr 07 2019
parent reply AltFunction1 <af1af1af1 af1.af1> writes:
On Sunday, 7 April 2019 at 10:05:26 UTC, kdevel wrote:
 In § 28.3 Pointers and the Garbage Collector [1] we read

    Do not add or subtract an offset to a pointer such that the 
 result points
    outside of the bounds of the garbage collected object 
 originally allocated.

 [...]
No the foo() code would work in D too but in D since we have a true array type with ptr+length you should not write this kind of code, which is not safe BTW.
Apr 07 2019
parent kdevel <kdevel vogtner.de> writes:
On Sunday, 7 April 2019 at 10:17:53 UTC, AltFunction1 wrote:
 On Sunday, 7 April 2019 at 10:05:26 UTC, kdevel wrote:
 In § 28.3 Pointers and the Garbage Collector [1] we read

    Do not add or subtract an offset to a pointer such that the 
 result points
    outside of the bounds of the garbage collected object 
 originally allocated.

 [...]
No the foo() code would work in D too but in D since we have a true array type with ptr+length you should not write this kind of code, which is not safe BTW.
I appreciate your constructive reply. What about the formal validity wrt. to the documentation? Is char *e = p + 10; outside of the bounds of the garbage collected object? Does for (q = p; q < e; ++q) depend on the ordering of pointers?
Apr 07 2019