Glib memory management

The “traditional” advice is, always use g_free() when freeing memory allocated by GLib functions; don’t use the C library’s free(). But in current gmem,c, we find the statement, “Since GLib 2.46 g_malloc() is hardcoded to always use the system malloc
implementation”, which would seem to imply that using the C library’s free() should be OK. Or am I missing something here?

For me the point is not just academic. I’m working with a large code base which for historical reasons mixes GLib and standard C memory allocation, for strings in particular (that is, malloc and calloc versus, for example, g_strdup_printf and g_file_get_contents). Right now I’m trying to ensure that the freeing function always matches the allocator, but it would make life a lot easier if I could be sure that for GLib >= 2.46 I don’t have to make that distinction and could use free() regardless.

(Yes, I know I could rejig all the string-allocation code to use only GLib or only standard C, but that would be a huge and painful job, only worth doing if I were sure there’s not an easy alternative.)

IIRC in the past was possible to tell GLib to use another set of functions for memory allocation, but not anymore. I would love if that still possible, so I could tell Glib to use the Crystal language GC malloc/free and not need to do a lot of things to let this marriage of GLib and a GCed language work in Crystal language gobj bindings.

While it is true that g_malloc and g_free call into the system’s allocator these days, for code hygiene you should not mix calls. Both g_malloc and g_free also have dtrace and systemtap tracing probes inside them, for instance, and it’s better to keep them coupled.

2 Likes

It’s not possible because GLib uses static constructors to ensure that its internal global state gets consistently initialised once the library is loaded, and since the initialisation code also allocates memory, that prevents anybody from changing the allocator functions, as you’d end up deallocating memory with the wrong free function.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.