§ 28.3 Pointers and the Garbage Collector

kdevel kdevel at vogtner.de
Sun Apr 7 10:05:26 UTC 2019


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


More information about the Digitalmars-d-learn mailing list