gcx.h
is a working garbage collector, header-only. It is a reference-counting garbage collector but it does not matter if you increase/decrease the refcount because if you dump an entire arena (aka 'frame') all the allocated memory pointers will get dumped alongside.
This is a very simple garbage collector. I have created it as a temporary solution for my projects, until I develop something more complex and sophistated. It's only hundred-odd lines. It is a header-only library, has a header guard and all the functions are static-inlined. You can include this file once in your file, and you can include it again because the functions are local to a single file. Alternatively, you can wget this file as a C file, remove the static keywords, and use it as a proper source file. It's entirely up to you.
As I said in the title, it is an arena-based garbage collector. Every arena is called a frame_t
structure. The 'proper' way to use this garbage collector:
1- Create a frame/arena for every, or every other, structure/portion of your program. 2- Every time you need to allocate memory, request a 'subframe'. 3- Allocate/deallocate the subframe as needed. 4- Every time you need a copy of the data, request a copy, and the refcount shall increase automatically. Every time you need to get rid of the data, use the proper function, and the reference shall decrease. 5- If you have the resources, you can automatiically increase the refcounts --- it does so by looking in the static region of the program, and below (or above, according to how you look at it) the program break for instances of that pointer --- and increase it by one if it sees the pointer. Keep in mind that this aspect is prety so-and-so. Don't rely on it much. 6- Whenever you need to collect, you can call the function and it shall collect the dead references.
The example.c
file contains an example of using all the functions.
Thanks.