Magpie is a tool that performs a program transformation on C code to use a precise garbage collector. In a nutshell, it changes calls from malloc to GC_malloc and removes calls to free() from the code.

Magpie is written in Ocaml and uses the Cil framework. The tool is a single ocaml file that you can add to a Cil distribution, if you know what you are doing. Or you can download a prebuilt Cil distribution with Magpie already added to it, then you just have to build Cil the usual way: ./configure && make.
You also need the garbage collector implementation to link into the transformed code.

This work was funded by the NSF.


The following papers have been published about Magpie


For an illustration of what the program transformation looks like, compare these two files.
Before: before.c
After: after.c

Here are some pre-transformed programs that I have converted using Magpie. The original source is part of the tar file.
Lame mp3 encoder
Aterm - xterm replacement
Gnu sort


Generally speaking, using Magpie is a painless ordeal. All you must do is run the tool over all the C files you have and then recompile them, linking in the garbage collector. For lame and aterm this is certainly all I had to do. For sort I had to change some fancy gnu allocators to their naive counterpart, such as xnrealloc to realloc.

Step 1

Run the C source through the preprocessor. I like to put the resulting file in a different directory, usually called 'gc'.
$ gcc -E src/file.c -o gc/file.i

Step 2

Run Magpie over the preprocessed file.
cilly.asm.exe --out gc/file.c --noPrintLn --dooneRet --doallocanalysis gc/file.i

Step 3

Compile the file.
$ gcc -c gc/file.c -o gc/file.o

Step 4

Link the program together with the garbage collector. You will also have to compile gc_implementation.o, obviously.
$ gcc gc/file.o gc/gc_implementation.o -o program


If your project consists of multiple .c files, repeat steps 1-3 on each .c file. You may notice that running Magpie will produce a file called 'tuning.h'. This file stores the initialization functions that must be called for the garbage collector to work properly. gc/gc_tuning.h will #include this file, so if you want to move tuning.h then either give the appropriate -I flag so that tuning.h can be found or alter gc_tuning.h explicitly to use the path to tuning.h

Arguments to Magpie

The ocaml implementation was written by Jon Rafkind.