question about the garbage collector

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Mon Mar 5 00:32:08 PST 2007


Saaa wrote:
>> D's garbage collector only applies to things that are allocated via the
>> 'new' keyword in D code*.  C typically uses malloc, which the D garbage
>> collector can't even see, much less mess with.  If you use malloc and
>> free from D code, then what you allocate using malloc won't be garbage
>> collected, either.
> 
> And dynamic arrays, right?

Yes, he forgot to mention using operators '~' or '~=' on (dynamic) 
arrays, and setting their .length to a larger value.

> (rant below)
> 
> I had some really strange problems with the gc.
> In my main loop I had to read in .png files quite alot (using SDL_Image) and 
> place them on a SDL_Surface.
> I had this problem of sometimes iso the png a black screen would appear.
> (always the same place(changing the actual picture didn't change a thing))
> 
> I traced the problem down to this:
> array.length=1800000;
> 
> Without this line (the array wasn't even in use) there were no black 
> screens.

You need to be careful when passing references to GC-allocated data to 
non-D libraries (like SDL). (setting an array length to a larger value 
makes it GC-allocated even if it wasn't previously)
If references are (only) stored where the GC can't see them (e.g. in 
malloc()ed memory), the data will be deleted on the next GC run. This 
may be what's happening here...

> My best solution still > first line in main > disable(); > no problems and a 
> big array :D
> 
> I'll report my bug when I'm sure it is (making the program minimal somehow 
> :)
> Somehow setting the array length enables the gc and somehow the gc redirects 
> the pointer, I think... more info later :)

The current GC doesn't move objects. It just deletes them if it can't 
find any references to them.


More information about the Digitalmars-d-learn mailing list