【问题标题】:Implementing a Mark Sweep Garbage collector in C在 C 中实现标记清除垃圾收集器
【发布时间】:2015-07-13 04:43:54
【问题描述】:

我在 C 中遇到了这个问题,我必须实现一个垃圾收集器。我坚持这样一个事实,即我被赋予了 4 个功能来完成,并且不确定它们如何相互连接。我不知道该怎么办。这是我目前所拥有的:

void mygc() {
  //int **max = (int **) 0xbfffffffUL;   // the address of the top of the stack
  unsigned long stack_bottom;
  int **max =  (int **) GC_init();   // get the address of the bottom of the stack
  int* q;
  int **p = &q;    // the address of the bottom of the stack

  while (p < max) {
    //printf("0. p: %u, *p: %u max: %u\n",p,*p,max);
    mark(*p);
    p++;
  }

  //utilize sweep and coalesce (coalesce function already written)
}

void mark(int *p) {
  int i;
  int *ptr;
  //code here
}

void sweep(int *ptr) {
  // code here
}

int *isPtr(int *p) {  
 //return the pointer or NULL
  int *ptr = start;

  //code here
 }

【问题讨论】:

  • 变量;不使用“stack_bottom”。这会引发编译器警告。建议启用所有编译器警告,重新编译,修复警告,重新发布代码。鉴于发布的代码,还有其他几个编译器警告。请发布编译/链接的代码,以便我们调试问题
  • 如果您包含对每个功能预期完成的内容的描述,也许会有所帮助。
  • 顺便说一句,如果你还没有#t,你可能想看看boehm collector

标签: c garbage-collection mark-and-sweep


【解决方案1】:

如果您甚至不理解这个问题,也许最好与您的教学人员交谈。让您从这里开始是一般的想法。

  • mygc 显然是执行 GC 的顶级函数。
  • 调用mark 将内存位置/对象标记为正在使用。它还需要将该位置/对象引用的所有内存标记为正在使用(递归)。
  • 调用sweep 以取消标记所有先前标记的内存并收回(垃圾收集)那些未标记的位置。
  • 调用isPtr 来确定内存位置是否是指针(而不是任何其他数据)。 mark 使用它来了解是否需要标记内存位置。

所以把所有这些放在一起,一般的伪代码是:

mygc()
{
    loc_list = get stack extents and global variables
    foreach (p in loc_list) {
        if (isPtr(p)) {
            mark(p)
        }
    }

    foreach (p in heap) {
        sweep(p)
    }
}

显然有很多细节没有在那个伪代码中处理。但希望它足以回答您最初的问题,即这四个功能如何组合在一起。

【讨论】:

    猜你喜欢
    • 2014-11-08
    • 2012-04-16
    • 2011-06-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多