2

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);
Guillaume D
  • 2,202
  • 2
  • 10
  • 37
macro_controller
  • 1,469
  • 1
  • 14
  • 32
  • Not sure about `glib`, but why you'd want to do that anyways? – Sourav Ghosh Apr 04 '19 at 08:00
  • 2
    Why do you wonder? What is the problem you have that lead you to ask about this? Perhaps you should ask about that problem directly instead? – Some programmer dude Apr 04 '19 at 08:00
  • And generally, you can't free memory you haven't explicitly allocated. And once you called `g_free` once, the memory the pointer is pointing to is no longer allocated. – Some programmer dude Apr 04 '19 at 08:02
  • Thank you for the response, I am researching an existing code, so I simply need to know that. – macro_controller Apr 04 '19 at 08:02
  • @Someprogrammerdude I edited the question to show that the buffer was also allocated by g_malloc. The second part of your answer it's my question - is it dangerous or maybe somehow glib makes it safe to do it twice. – macro_controller Apr 04 '19 at 08:06

2 Answers2

5

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.

imz -- Ivan Zakharyaschev
  • 4,921
  • 6
  • 53
  • 104
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

tl;dr: No.

It’s exactly equivalent to calling free() on the same allocation twice, which leads to undefined behaviour.

Philip Withnall
  • 5,293
  • 14
  • 28