Click here to Skip to main content
15,125,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to understand how the garbage collector should work and maybe write it myself in C. I want to create my own stack and stuff variables there, as well as write a garbage collector for it. And I cannot understand how the program should find out that the object is not used?

What I have tried:

I've tried to write my own stack.
Updated 30-May-21 8:11am

You are looking at a lot of complicated work there - it's not going to be a simple job at all.
But this may help: Writing a Mark-Sweep Garbage Collector – Dmitry Soshnikov[^]
Garbage collection normally isn't done in C++. Code is expected to free objects explicitly (e.g., by using delete) or implicitly (when a unique_ptr goes out of scope).

However, here's an article[^] about a garbage collector that I wrote. Objects are created in blocks allocated from pools, and a background garbage collector recovers objects that aren't "claimed" at the application level. This is basically a mark and sweep strategy, but applications must claim in-use objects because the system doesn't manage pointers and therefore can't tell which objects have owners. Applications are still expected to free objects explicitly, so the background garbage collector serves as a backup to recover from memory leaks.
For that you need to understand the concept of scope which means life time of an object. Here is some explanation of the scope in C++.

You must also understand the differences between heap and stack memory in C++.

You should read both sites carefully and understand them for your task or you will fail. ;-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900