Memory management 如何在glib';s GMemVTable结构

Memory management 如何在glib';s GMemVTable结构,memory-management,function-pointers,glib,Memory Management,Function Pointers,Glib,我在Ubuntu 14.04 64位上使用glib。我正在使用glib的内存监视器(函数g_mem_profile()打印内存使用情况和未释放的内存量)。 g_mem_配置文件显示~3k未被释放。其中一个已分配但未释放的块大小为252字节 我在想这样的事情:我将GMemVTable中的malloc函数替换为 gpointer test_malloc (gsize nBytes) { if (nBytes == 252) printf ("Gotcha!\n");

我在Ubuntu 14.04 64位上使用glib。我正在使用glib的内存监视器(函数g_mem_profile()打印内存使用情况和未释放的内存量)。 g_mem_配置文件显示~3k未被释放。其中一个已分配但未释放的块大小为252字节

我在想这样的事情:我将GMemVTable中的malloc函数替换为

gpointer test_malloc (gsize nBytes)
{
    if (nBytes == 252)
        printf ("Gotcha!\n");
    return malloc (nBytes);
}
这样我就可以进入调试器,在printf行中设置一个断点,然后检查分配这252字节的调用堆栈。 下面是我用来替换相应GMemVTable成员的代码:

static gpointer test_malloc (gsize nBytes)
{
    if (nBytes == 252)
        printf ("Bin hier!!!! %" G_GSIZE_FORMAT, nBytes);
    return malloc (nBytes);
}

static void memory_helper ()
{
    /*kpodcast_mem_vtable.malloc = glib_mem_profiler_table->malloc;*/
    kpodcast_mem_vtable.malloc = test_malloc;
    kpodcast_mem_vtable.realloc = glib_mem_profiler_table->realloc;
    kpodcast_mem_vtable.free = glib_mem_profiler_table->free;
    kpodcast_mem_vtable.calloc = glib_mem_profiler_table->calloc;
    kpodcast_mem_vtable.try_malloc = glib_mem_profiler_table->try_malloc;
    kpodcast_mem_vtable.try_realloc = glib_mem_profiler_table->try_realloc;

}
当我使用此代码时,程序崩溃:

*** Error in `./kpodcast': corrupted double-linked list: 0x00000000024de530 ***
当我取消注释第一行以便使用glib_mem_profiler_table->malloc时,它不会崩溃。 我做错了什么?这一定与我使用函数指针的方式有关

非常感谢
Kai

我不知道您为什么会看到此错误消息,但可能还有其他方法可以完成您尝试执行的操作

事实证明,GLib有一种内置机制,用于捕获特定大小的内存分配,在构建库时启用调试功能(因此您可能需要构建并安装自己的库本地副本)。在GLib发行版中:

Some code portions contain trap variables that can be set during
debugging time if G_ENABLE_DEBUG has been defined upon compilation
(use the --enable-debug=yes option to configure for this, macros.txt
covers more details).
Such traps lead to immediate code halts to examine the current
program state and backtrace.
Currently, the following trap variables exist:

...

static volatile gulong g_trap_malloc_size;
        If set to a size > 0, g_free(), g_realloc() and g_malloc()
        respectively, will be intercepted if the size matches the
        size of the corresponding memory block to free/reallocate/allocate.
        This will only work with g_mem_set_vtable (glib_mem_profiler_table)
        upon startup though, because memory profiling is required to match
        on the memory block sizes.
实现的
静态volatile
声明和断点触发行为使我认为您应该在调试器中加载应用程序,然后将一个值填充到此变量中,让程序运行。当进行指定大小的分配时,库将捕获回调试器中,允许您检查回溯跟踪,并查看分配在代码中的位置