我在 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
}
最佳答案
如果您甚至不明白这个问题,也许最好与您的教学人员交谈。为了让您开始,这里是总体思路。
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)
}
}
显然有很多细节没有在伪代码中处理。但它应该足以回答您最初的问题,即这四个功能如何组合在一起。
关于c - 在 C 中实现 Mark Sweep 垃圾收集器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019260/