I'm implementing mark-and-sweep garbage collection in a simple scripting language API I'm working on and have been reading about various implementations of garbage collection. API's such as Lua use mark-and-sweep with white, gray and black lists.
The problem is, I can't seem to find explanation of why there are such lists and why they are put into these specific colours.
In my current, trivial implementation, I simply use "dead" or "alive" states. In the sweep, the dead objects are deleted. I'm using the native heap so I'm not doing any moving in my GC.
I'm writing it in C.
// Performs a full garbage collection
void GorCollect(GorContext *ctx)
{
Value *v, *end;
Collectable *c, *n;
// mark stack references
end = ctx->stack + ctx->stackTop + 1;
v = ctx->stack;
while(v != end)
{
if (gvisgc(v) && v->v.gc) // mark if a collectable obj
Mark(v->v.gc);
v = v++;
}
// mark global references
if (ctx->global)
Mark((Collectable *)ctx->global); // ctx->global is a collectable obj
// perform sweep
c = ctx->gchead; // full list of collectable objs
ctx->gchead = 0;
while(c) {
n = c->next;
// destroy unmarked collectable
if (!c->marked)
FreeCollectable(ctx, c);
// rebuild gc list (singly-linked)
else
{
c->marked = 0;
if (!ctx->gchead)
c->next = 0;
else
c->next = ctx->gchead;
ctx->gchead = c;
}
c = n;
}
}