两次释放 glib 缓冲区是否安全?

Is it safe to free a glib buffer twice?

两次释放 glib g_malloc 函数分配的缓冲区是安全的还是禁止的?

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

来自 glib/gmem.c(假设您没有 g_mem_set_vtable 做一些花哨的事情):

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));
}

glib_mem_vtable.free(mem) 将调用 standard_free(mem),后者只会调用 free(mem)。因为这样做是无效的:

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

在同一个内存指针上两次调用 g_free 是无效的,因为它在其参数上内部调用 free

tl;dr: 没有。

这完全等同于在同一分配上调用 free() 两次,即 leads to undefined behaviour