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

时间:2019-04-04 07:59:05

标签: c memory-management glib double-free

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

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

2 个答案:

答案 0 :(得分:4)

glibc/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

答案 1 :(得分:1)

tl; dr:否

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