3 ms·
Interesting write up. I am curious about the usage of this framework. One thing in reference counting’s favor is that it is hard to screw up. You just use the r
by celeritascelery 2y ago
Interesting write up. I am curious about the usage of this framework. One thing in reference counting’s favor is that it is hard to screw up. You just use the rc type and when it is no longer accessible it will magically get freed. That is how GC works in a high level language too, you almost never need to think about it.
Let’s look at the example from the docs:
SWL_GCArena gc = swl_gc_arena_new(<starting-capacity>);
int* foo = swl_gc_alloc(&gc, 5000, alignof(int), NULL);
int* bar = swl_gc_alloc(&gc, 16000, alignof(int), NULL);
int* baz = swl_gc_alloc(&gc, 3000, alignof(int), NULL);
// foo and baz are roots
SWL_GC_COLLECT(&gc, SWL_ROOT(foo), SWL_ROOT(baz));
// bar is gone, poof
If you try to access bar at the end you get a use after free. I am pretty sure if you tried to access foo again it would trigger the same problem, because it is a pointer directly to int and not an indirection. What happens if you pass a non-arena pointer to SWL_ROOT? What happens if you have multiple arenas and you mix and match them?
There are many ways you could trivially shoot yourself in the foot in large program. It is a lot less “idiot-proof” than simple reference counting. The fact that you create each piece of memory and then have to manually pass it back to the root macro on each collection is very similar to the “malloc/free” dance we want to try and avoid.
The rooting issue is something I tried to tackle in my GC for rust[1]. Essentially making low level GC "idiot proof".
[1] https://coredumped.dev/2022/04/11/implementing-a-safe-garbage-collector-in-rust/ https://coredumped.dev/2022/04/11/implementing-a-safe-garbag...
- sirwhinesalot 2y agoThe idea is that this would be used in a language backend, so the compiler would track the roots for you. Note that in C ref counting is also rather error prone in that you can increment or decrement a reference the wrong number of times. But I agree this is not the best thing to do manually. The main advantage is that you only need to call collect in 1 place in your whole app. A lot easier to get right than having free all over the place. EDIT: placed your article on my reading list, thanks for sharing it!
- forrestthewoods 2y ago> One thing in reference counting’s favor is that it is hard to screw up. Well, circular references will cause your RC objects to never ever drop. So then you have to start using a bunch of Weak references. And it can very quickly become a confusing and hard to understand mess. The cost of a memory leak is significantly lower than the cost of a use after free. But disentangling the graph of refcounts can be super painful.