gpt4 book ai didi

c - Boehm GC如何为C程序工作?

转载 作者:太空狗 更新时间:2023-10-29 16:35:45 25 4
gpt4 key购买 nike

我检查了 Boehm GC。 C/C++ 的 GC。

我知道标记清除算法。我很好奇的是它如何在整个 C 内存中只获取指针。我对C内存的理解只是一个普通的字节数组。是否可以确定内存中的值是否为指针?

最佳答案

Boehm GC 是一个保守的收集器,这意味着它假定所有内容(在指针边界上)都是指针。这意味着它可以找到误报引用,例如恰好具有堆中地址值的整数。因此,一些 block 在内存中的停留时间可能比使用非保守收集器的时间长。

这是来自 Boehm's page 的描述:

The garbage collector uses a modifiedmark-sweep algorithm. Conceptually itoperates roughly in four phases, whichare performed occasionally as part ofa memory allocation:

  1. Preparation Each object has an associated mark bit. Clear all markbits, indicating that all objects arepotentially unreachable.
  2. Mark phase Marks all objects that can be reachable via chains ofpointers from variables. Often thecollector has no real informationabout the location of pointervariables in the heap, so it views allstatic data areas, stacks andregisters as potentially containingpointers. Any bit patterns thatrepresent addresses inside heapobjects managed by the collector areviewed as pointers. Unless the clientprogram has made heap object layoutinformation available to thecollector, any heap objects found tobe reachable from variables are againscanned similarly.
  3. Sweep phase Scans the heap for inaccessible, and hence unmarked,objects, and returns them to anappropriate free list for reuse. Thisis not really a separate phase; evenin non incremental mode this isoperation is usually performed ondemand during an allocation thatdiscovers an empty free list. Thus thesweep phase is very unlikely to toucha page that would not have beentouched shortly thereafter anyway.
  4. Finalization phase Unreachable objects which had been registered forfinalization are enqueued forfinalization outside the collector.

您还应该知道,需要为 Boehm GC 提供一组“根”,它们是标记清除算法的起点。堆栈和寄存器自动成为根。您需要显式添加全局指针作为根。


编辑:在评论中,有人指出了对一般保守收藏家的一些担忧。确实,看起来像指向收集器的堆指针的整数会导致内存无法释放。这并不像您想象的那么严重。程序中的大多数标量整数用于计数和大小,并且相当小(因此它们看起来不像堆指针)。您通常会遇到包含位图、字符串、 float 据或任何此类数据的数组的问题。 Boehm GC 允许您使用 GC_MALLOC_ATOMIC 分配一个 block ,它向收集器指示该 block 将不包含任何指针。如果你看gc_typed.h ,您还将找到指定 block 的哪些部分可能包含指针的方法。

也就是说,保守收集器的一个基本限制是它不能在收集期间安全地移动内存,因为指针重写是不安全的。这意味着您不会获得压缩的任何好处,例如减少碎片和提高缓存性能。

关于c - Boehm GC如何为C程序工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4796379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com