Search code examples
cmemory-managementglibdouble-free

Is it safe to free a glib buffer twice?


Is it safe or forbidden to free twice a buffer allocated by glib g_malloc function?

char *buffer = g_malloc(10);
g_free(buffer);
g_free(buffer);

Solution

  • From glib/gmem.c (Assuming you didn't do g_mem_set_vtable to something fancy):

    static void
    standard_free (gpointer mem)
    {
      free (mem);
    }
    ...
    /* --- variables --- */
    static GMemVTable glib_mem_vtable = {
      standard_malloc,
      standard_realloc,
      standard_free,
      standard_calloc,
      standard_try_malloc,
      standard_try_realloc,
    };
    ...
    void
    g_free (gpointer mem)
    {
      if (G_UNLIKELY (!g_mem_initialized))
        g_mem_init_nomessage();
      if (G_LIKELY (mem))
        glib_mem_vtable.free (mem);
      TRACE(GLIB_MEM_FREE((void*) mem));
    }
    

    The glib_mem_vtable.free(mem) will call standard_free(mem) which will just call free(mem). As it is invalid to do:

     void *mem = malloc(1);
     free(mem);
     free(mem); // undefined behavior
    

    As much it is invalid to call g_free on the same memory pointer twice, as it internally calls free on it's argument.