c - libgc : why this code leaks?

标签 c garbage-collection boehm-gc

我尝试在这个简单的代码中使用 libgc(BDW 垃圾收集器)。

请注意,该引用仅保留到假“列表”中的最后一个节点,因此,事件集只有最后两个节点。

// thanks to @chill for this example
#include <gc.h>

struct list {
    struct list* next;
};

int main() {
    GC_INIT();
    struct list *last = NULL;
    for (;;) {
        struct list* nuo = GC_MALLOC(sizeof(struct list));
        nuo->next = NULL;
        // if next line is commented, then no leakage
        if (last) last->next = nuo;
        last = nuo;
    }
}

但它无法保持在内存限制内:

$ gcc -O0 gc.c -lgc -o gc

$ GC_MAXIMUM_HEAP_SIZE=100000000 ./gc

GC Warning: Out of Memory!  Trying to continue ...
GC Warning: Out of Memory!  Trying to continue ...
GC Warning: Out of Memory!  Trying to continue ...
GC Warning: Out of Memory!  Trying to continue ...
GC Warning: Out of Memory! Heap size: 95 MiB. Returning NULL!
Segmentation fault

我做错了什么? Ubuntu 15.04 x86_64 gcc 4.9.2 libgc 7.2d-6.4

更新:我刚刚从 https://github.com/ivmai/bdwgc 编译了主干版本它看起来工作正常。因此,bug 仅存在于 7.2d 或打包到 Ubuntu 的版本中。

更新:从源代码编译的 libgc 7.2f 也可以正常工作。所以这只是 Ubuntu 和 Debian 的版本问题。

最佳答案

这可能只是一个错误,但也可能是错误指针的受害者。 BDWGC是保守型GC;如果一个单词“看起来像”一个指针恰好指向 GC_malloced 内存,则该内存将被保留。如果某个假指针恰好指向您的列表节点之一,它会被意外保留,并且它指向的所有节点也会被保留。

从弱GC鲁棒性角度进行讨论。详细信息请参阅以下论文:

http://www.hpl.hp.com/techreports/2001/HPL-2001-251.pdf

一个常见的习惯是当节点不使用时手动取消下一个链接。

关于c - libgc : why this code leaks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31380641/

相关文章:

c++ - 将 C++ 代码转换为 C 时程序崩溃

c - OpenMP并行化

ruby-on-rails - Ruby 中的内存管理

c - 在多个线程中独立运行 Boehm GC

memory-management - 分代垃圾回收和增量垃圾回收有什么区别?

c - remquo : argument reduction?

c# - 如果我将一个控件绑定(bind)到另一个控件,并且其中一个控件死亡,那么绑定(bind)会发生什么情况?

Java Swing - TableLayout - 未从布局中删除的组件

c - Boehm GC android sigsegv on load_gc

c - 输入中固定数据的非阻塞读取