The University of Queensland Homepage
School of ITEE ITEE Main Website

 Using the Boehm Garbage Collector with existing C++ code

Some time ago, I used the Boehm garbage collector with the Boomerang open source decompiler. Boomerang is a C++ project of some 130 KLOC (but more than half of that is generated from specification and parser files). The documentation for this collector is a little contradictory; they claim that collected and non-collected objects can work with each other, and yet warn that objects pointed to only by the system heap may be prematurely collected. Both statments are true in a sense; what it means in practice is that you need to override the "operator new" and "operator delete" functions.

You have the choice of collecting everything, including STL objects, or collecting only some classes. You collect specific classes by deriving them from class gc.

I found that to have STL objects uncollected, I had to add these functions to the Boomerang code:

void* operator new(size_t n) {
    return GC_malloc_uncollectable(n);
}

void operator delete(void* p) {
    GC_free(p);
}

It is simple to collect everything as well: replace the call to GC_malloc_uncollectable with a call to GC_malloc, and replace the call to GC_free with no code. In fact, that's what we do now, so we don't have to derive any classes from class gc. That makes for the minimum changes to the code to incorporate the garbage collector.

This overriding seems to be necessary because gcc 3 (and probably other compilers) don't actually call malloc from operator new.

You can also collect specific STL objects, like this:

#include <gc/gc_allocator.h>
...
std::map<key, type, std::less<key>, gc_allocator<pair<const key, type> > > mapname;

or the old way like this:

#include <gc/new_gc_alloc.h>
...
std::map<key, type, std::less<key>, gc_alloc> mapname;

Note: gc_alloc.h is for even older STL implementations.

However, it could be a lot of work adding this to all STL containers of pointers. It is not clear to me whether there is a real advantage to using allocators like this.

When debugging or evaluating the collector, you may find

export GC_PRINT_STATS=1

to be useful.

Last modified 30/Jun/2005: gc_allocator.