While purists will say using a garbage collector in C is blasphemy, it has been shown that very often code runs faster when a garbage collector is in use.
Also, sometimes it occurs that you have to leave a function due to a error case and don’t want to copy all the cleanup to every exit point. You should if you can.
When you have memory leaks, and don’t use a garbage collector, your program will also become slower and slower.
However, luckily good garbage collectors exist and are easy to use. E.g. the good old boehm gc. Linux distributors usually provide a package.
You can include my memory.h and just call mem_malloc, mem_calloc, mem_realloc, mem_free instead of without the mem. for people that don’t have boehmgc installed, you still remain compatible. Of course there are other ways too.
#ifndef MEMORY_H_
#define MEMORY_H_
#include "debug.h"
#define FREEMSG(x) IFSEGV dump_p("about to free", (void*)x);
#ifdef WITHOUT_GARBAGE_COLLECTOR
#define mem_malloc(x) malloc(x)
#define mem_calloc(n,x) calloc(n, x)
#define mem_realloc(p,x) realloc(p,x)
#define mem_free(x) { FREEMSG(x); free(x); (x) = NULL; }
#else
#include <gc.h>
#define mem_malloc(x) GC_malloc(x)
#define mem_calloc(n,x) GC_malloc((n)*(x))
#define mem_realloc(p,x) GC_realloc((p),(x))
#define mem_free(x) { FREEMSG(x); (x) = NULL; }
#endif
#endif /* MEMORY_H_ */
Recent Comments