5
votes

I've been trying to create a garbage collector in c++, i've designed it as a base class to all of mine, called garbageCandidate, which holds a static vector containing pointers to garbageCandidate with every garbageCollector instance pushing "this" on the vector.

Then a static function comes and delete all the pointers in the static vector.

At the very begining of the deleting function (delete on first pointer) i get an error stating delete was used on invalid pointer...

Does this have to do with static/dynamic binding? I mean : is the delete operator unable to act as expected since i call delete on a "father" class and it is in fact a child ?

Could a way of avoiding this be to create virtual destructors? (or a virtual delete function)?

or did i completely missed something?

ps:all objects used for test where created dynamically.

2
Did you make the dtor virtual in your garbageCandidate class? - Jerry Coffin
No, it has nothing to do with static/dynamic binding. - Daniel Kamil Kozar
That would only be a problem if the destructor is not virtual. But it's hard to say without seeing any code. Can you come up with an SSCCE? - Joseph Mansfield
If you are deleting derived objects through pointers-to-base, then the base destructor must be virtual. - Oliver Charlesworth
Make sure you never create garbage-collected objects on the stack. - David Schwartz

2 Answers

0
votes

Is there a reason you're rolling your own custom garbage collector? If all your objects are created dynamically, then why aren't you using boost's smart pointers (like boost::shared_ptr) which essentially uses RAII to give you a well tested garbage collection solution?

I ask because usually in the course of software development life cycle of a project, you end up fixing bugs in the code you wrote yourself (most of the time, at least). So is there a reason you're re-inventing the wheel?

0
votes

Rather than rolling your own GC, I think you should be using the Boehm Conservative GC or smart pointers. Neither is perfect:

In spite of this, either of Boehm GC or Smart pointers would be less implementation and maintenance effort than rolling your own solution.