

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 9
click for more info
Not enough gems
Cost: 6 gems
1: Handling Cycles
incomplete
2: Pros and Cons
incomplete
3: Stack Frames
incomplete
4: Tracking Objects
incomplete
5: Free
incomplete
6: Frame References
incomplete
7: Mark and Sweep
incomplete
8: Mark
incomplete
9: Trace
incomplete
10: Sweep
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
Recall the refcount_free function that you wrote in the previous chapter. It should have looked something like this:
void refcount_free(snek_object_t *obj) {
switch (obj->kind) {
case INTEGER:
case FLOAT:
break;
case STRING:
free(obj->data.v_string);
break;
case VECTOR3: {
snek_vector_t vec = obj->data.v_vector3;
refcount_dec(vec.x);
refcount_dec(vec.y);
refcount_dec(vec.z);
break;
}
case ARRAY: {
snek_array_t *array = &obj->data.v_array;
for (size_t i = 0; i < array->size; i++) {
refcount_dec(array->elements[i]);
}
free(array->elements);
break;
}
}
free(obj);
}
Let's rewrite our free-ing logic for mark-and-sweep. Because the virtual machine is the one tracking objects, all of the refcount_dec work can be removed! There's some very cool tricks coming up for mark-and-sweep to manage this, but for now you can just trust me that we'll correctly free any of the contained elements if they are no longer alive.