How does the GC work?

Bill Baxter dnewsgroup at billbaxter.com
Thu Aug 23 23:27:37 PDT 2007


Huang F Guan wrote:
> // A simple program
> int test()
> {
> 	int *a = new int;
> 	*a = 1;
> 	return 0;
> }
> 
> int main()
> {
> 	test();
> 	return 0;
> }
> 
> //======================
> Hi, I wonder how the gc works in my D programs. This is a test program. In the test function, I allocate a memory space for an integer pointer and don't delete it by the end of the function. I think the garbage collector will help me do this. But when I debugged my program, I couldn't find any deallocate behaviors until the end of the test function. Finally I found that gc deallocate it when the program was going to exit.
> 
> Doesn't gc deallocate the allocated momory at once when I no more use it?
> 

It isn't a reference counting garbage collector.  It's a mark-and-sweep 
type.  That means that every so often it goes through the all the memory 
  marks all the things that it finds references to (both on the GC heap 
and on the current stack), and deletes all the rest.  The "every so 
often" part generally means during allocations.  So the next time you 
use the GC to alloc something, it should delete the garbage.

If you want the behavior of destruction as soon as it goes out of scope, 
then you can use a scope class.

--bb



More information about the Digitalmars-d mailing list