简体   繁体   English

在C中实现标记扫描垃圾收集器

[英]Implementing a Mark Sweep Garbage collector in C

I have this problem in C where I have to implement a garbage collector. 我在C中必须实现垃圾收集器的问题。 I'm stuck on the fact that I was given 4 functions to complete and not sure how they connect to one another. 我坚持这样一个事实,我得到了4个函数来完成,并且不确定它们如何相互连接。 I'm not sure what to do. 我不确定该怎么办。 This is what I have so far: 这是我到目前为止的内容:

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
 }

If you don't even understand the question perhaps it's best to speak to your teaching staff. 如果您甚至不理解这个问题,也许最好与您的教学人员交谈。 To get you started here's the general idea. 为了让您入门,这是一般的想法。

  • mygc is obviously the top level function that does the GC. mygc显然是执行GC的顶级功能。
  • mark is called to mark memory location/object as in use. mark被称为标记存储器的位置/对象作为在使用中。 It also needs to mark all memory referenced by that location/object as in use (recursive). 它还需要将该位置/对象引用的所有内存标记为正在使用(递归)。
  • sweep is called to unmark all the previously marked memory and to claim back (garbage collect) those locations that are not marked. 将调用sweep以取消标记所有先前标记的内存,并索回(垃圾回收)那些未标记的位置。
  • isPtr is called to determine whether a memory location is a pointer (as opposed to being any other data). isPtr以确定存储位置是否是指针(而不是其他任何数据)。 This is used by mark to know whether a memory location needs to be marked or not. mark使用它来知道是否需要标记存储位置。

So putting that all together the general pseudo code is: 因此,将所有通用伪代码放在一起:

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)
    }
}

There are obviously lots of details not dealt with in that psuedo code. 显然,该伪代码中没有处理很多细节。 But it should hopefully be enough to answer your original question which is how the four functions fit together. 但它应该足以回答您的原始问题,即这四个功能如何配合在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM