Garbage Collection Pitfall in C++ but not in D?
Alex Rønne Petersen
alex at lycus.org
Fri Jul 6 21:10:37 PDT 2012
On 07-07-2012 05:02, akaz wrote:
> On Friday, 6 July 2012 at 21:10:56 UTC, Simon wrote:
>> On 06/07/2012 16:39, Alex Rønne Petersen wrote:
>>> On 06-07-2012 16:07, Denis Shelomovskij wrote:
>>>> 06.07.2012 17:43, akaz пишет:
>>
>> Never mind what D says, even in C/C++ just doing the p += 10 is invalid.
>>
>> Creating a pointer that points at invalid memory is just as wrong as
>> dereferencing it would be.
>
> Actually, p+10 could still be valid memory.
>
> OTOH, the other case that's given on the original page is this one:
>
> int* p = new int;
> int x = reinterpret_cast<int>(p); // non-portable
This will fail on a 64-bit system, but
> p=0;
will work fine on a 32-bit system since the pointer is still
conservatively visible in x. Not many GCs scan the stack and static data
segments precisely, since it's often not worth it. This is the case for
D's GC.
(Make x size_t and it will always work. In D, anyway.)
> // ... collector may run here ...
> p = reinterpret_cast<int*>(x);
> *p = 10; // can we be sure that the int is still there?
Yes (under the conditions described above).
>
> So, the pointer could sometimes simply disappear temporarily, without
> becoming invalid (well, p==NULL is somewhat invalid, bt it could have
> been p=&q). Just some allocated memory is no longer referenced for the
> time being and this could trigger the GC without protection (except
> disabling GC for the entire application).
>
> Won't some functions doing just what addRange() and removeRange() do
> solve that kind of problem (if necessary)? That means, forbidding the GC
> to scan some memory area for some time?
I think you misunderstand what those functions do. See my earlier reply.
addRange() merely lets the GC know that a region of memory may contain
pointers into GC memory on every machine word boundary of the region.
This region of memory is scanned conservatively, i.e. an integer inside
the region which looks like a pointer will keep the memory that the
pointer value would point into alive. The stack is always scanned by the
GC, and in D's case, conservatively. removeRange() just removes a root
memory range; no magic there.
--
Alex Rønne Petersen
alex at lycus.org
http://lycus.org
More information about the Digitalmars-d-learn
mailing list