Author: Samuel WilliamsWhen: Saturday, 03 September 2011
I was interested to learn more about garbage collection. The idea is not complex, but obviously writing a fast, portable implementation that deals with all the edge cases is a challenge.
However, I just wanted to try something simple - detecting when pointers are no longer directly on the stack is a good starting point, so I implemented that with a very basic mark and sweep algorithm.
This garbage collector will only scan the stack for allocated memory pointers. It isn't portable or efficient. However, I enjoyed writing the code and trying it out. Maybe I'll make something more complete in the future.
Because this garbage collector is designed to be very simple, it has many limitations:
Assumes pointers on the stack will be aligned.
Doesn't consider global variables (including class/function static variables).
Only works with a single stack/thread.
Doesn't consider pointers in registers, or attempt to flush these to the stack before collecting.
The calculation of the stack is probably not portable.
Feel free to improve the code and send suggestions. Ideally, I want to keep it as easy to understand as possible.