Memory leak when using garbage collection with glib

I try to integrate the Boehm garbage collector with GLib on Linux, but in one case I find that it does not free memory: when I call g_strsplit many times, it runs out of memory and segfault. The README for the garbage collector warned that there might be a problem finding pointers inside dynamic libraries and might require the use of GC_add_roots.

To test this, I copied all the relevant code from GLib to the source file, and did not refer to libglib-2.0.so at all. This eliminated the segfaults, which tells me that this is really a problem. However, there is no documentation on how to use GC_add_roots to fix it. Can anybody help me?

Here is the code that causes a memory leak:

#include <glib.h> #include <gc.h> void no_free(void *mem) {} int main() { g_mem_gc_friendly = TRUE; GMemVTable memvtable = { .malloc = GC_malloc, .realloc = GC_realloc, .free = no_free, .calloc = NULL, .try_malloc = NULL, .try_realloc = NULL }; g_mem_set_vtable(&memvtable); for (int i = 0; i < 10000; i++) { char **argv = g_strsplit("blah", " ", 0); argv[0][0] = 'a'; // avoid unused variable warning } return 0; } 
+5
source share
1 answer

Since GLib 2.46, g_mem_set_vtable() does nothing , so there is no way to make it work at the GLib level using modern GLib, GLib now unconditionally uses the allocator from libc when calling g_malloc() , g_new() , etc. It still uses its own GSLice when you explicitly use g_slice_*() , but also asks for its block allocation from the libc allocator.

I suggest you try to integrate the libc level garbage collector. There's an old implementation article using glibcs ​​malloc hooks , which essentially match GMemVTable , but at the glibc level instead of the GLib level. I have not tried this, so I do not know how well it works in practice.

+1
source

Source: https://habr.com/ru/post/1210638/


All Articles