Memory Corruption with AAs

Michel Fortin michel.fortin at michelf.com
Sun Apr 4 07:12:15 PDT 2010


On 2010-04-04 09:45:36 -0400, dsimcha <dsimcha at yahoo.com> said:

> == Quote from Michel Fortin (michel.fortin at michelf.com)'s article
>> Question: if the container's memory isn't garbage-collected, how do you
>> implement iterators, eh, ranges so that they are still memory-safe?
> 
> The way I'm picturing this being implemented is that a GC'd class 
> instance exists
> at the top level, and then the internal implementation-detail storage that the
> class uses is implemented via malloc and free.  This storage would get freed in
> the class finalizer when the instance is GC'd.  In this case all you'd 
> need to do
> is make the range hold a reference to the class instance so it wouldn't 
> be GC'd.

That wouldn't work with realloc: realloc copies to a new location then 
frees the old memory if it cannot expand in place. You can't keep the 
old copy allocated.

I've been thinking of another method to ensure safety: don't allow 
expanding a container as long as there are ranges pointing to it. 
Easily implemented with a reference count. For instance, if you have a 
vector container, expanding the container would invalidate ranges. 
Instead of allowing ranges to become invalid and potentially dangerous, 
just disallow expanding the container. The range would contain a 
pointer to its upper and lower bound, and a pointer to the container to 
increment the reference count when it's copied and decrement it when 
it's destroyed.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list