貝姆垃圾收集器
Boehm-Demers-Weiser garbage collector,也就是著名的Boehm GC,是計算機應用在C/C++語言上的一個保守的垃圾回收器,可應用於許多經由C/C++開發的專案,同時也適用於其它執行環境的各類程式語言,包括了GNU版Java編譯器執行環境,以及Mono的Microsoft .NET移植平台。同時支援許多的作業平台,如各種Unix作業系統,微軟的作業系統(Microsoft Windows),以及麥金塔上的作業系統(Mac OS X),還有更進一步的功能,例如:漸進式收集(incremental collection),平行收集(parallel collection)以及終結語意的變化(variety of finalizer semantics)。
範例
垃圾收集器作用於未變性的(unmodified)C程式,只要簡單的將malloc呼叫用GC_malloc取代,將realloc取代為GC_realloc呼叫,如此一來便不需要使用到free的函式。下列的程式碼展示出如何用Boehm取代傳統的malloc以及free。.
#include "gc.h"
#include <assert.h>
#include <stdio.h>
int main()
{
int i;
GC_INIT();
for(i = 0; i < 10000000; I)
{
int **p = (int **) GC_MALLOC(sizeof (int *));
int *q = (int *) GC_MALLOC_ATOMIC(sizeof (int));
assert(*p == 0);
*p = (int *) GC_REALLOC(q, 2 * sizeof (int));
if(i % 100000 == 0)
printf("Heap size = %d\n", GC_get_heap_size());
}
return 0;
}
外部链接
This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.