3 ms·
The simplest way to do this is to use the low bit of the address (so long as you align your memory to at least 2 bytes this is fine as all addresses will end in
by necubi 6y ago
The simplest way to do this is to use the low bit of the address (so long as you align your memory to at least 2 bytes this is fine as all addresses will end in 0) as a marker for whether you've already visited that pointer.
See https://en.wikipedia.org/wiki/Tracing_garbage_collection#Na%C3%AFve_mark-and-sweep https://en.wikipedia.org/wiki/Tracing_garbage_collection#Na%...
And yes, you're correct that GCs handle cycles without issue (that's a large part of the reason to use tracing GC over other memory management strategies like ObjC's auto-reference counting).
- magicalhippo 6y agoDon't know if any GCs use it, but if modifying the pointers is not possible then one alternative is Floyd's cycle-finding algorithm[1] which uses constant storage (two pointers). [1]: https://en.wikipedia.org/wiki/Cycle_detection#Floyd.27s_Tortoise_and_Hare https://en.wikipedia.org/wiki/Cycle_detection#Floyd.27s_Tort...
- necubi 6y ago"Finding cycles" is not really the problem a GC is trying to solve. It's trying to find all of the non-reachable data, across a possibly cyclic graph. It just has to ensure that it doesn't loop infinitely while traversing that graph.
- magicalhippo 6y agoAnd that would be the reminder not to post before breakfast :) Still, fun algorithm.
- throwaway_pdp09 6y agoI purposefully used the word 'efficient' in my original post. Of course you can find cycles many ways, but floyd's (or similar) are not acceptably fast and never can be in general.