looking for some solutions? You are welcome.

SOLVED: Multiple pointers and Mark & Sweep


I am trying to implement a small script language and was going to decide which garbage collection algorithm fits my benefits. I chose Mark & Sweep however i think i misunderstood the concept.

Let's say an arbitrary function is called and it creates following variables(Probably they don't have names but for the sake of simplicity assume they created in this function).

f() {
    /*f creates following variables*/     
    x = (1,2,(3,4,(5,6))); //this is tuple
    a = x;
    y = x[2];
    z = y[2];
    p = (10,y);

In the above example, everything is an object(integers, strings, tuples, doubles etc.) and tuples hold pointers to its objects. Moreover, every object lives in the heap. When function goes out of scope it has to delete allocated variables. Function scope looks like following.

|     |
|  x  +---------->(1,2,+)
+-----+           ^    |
                  |    v
+-----+           |    (3,4,+)
|     |           |    ^    |
|  a  +-----------+    |    v
+-----+                |    (5,6)
                       |    ^
+-----+                |    |
|     |                |    |
|  y  +----------------+    |
+-----+                |    |
                       |    |
+-----+                |    |
|     |                |    |
|  z  +---------------------+
+-----+                |
+-----+                |
|     |                |
|  p  +----------->(10,+)

All variables (a,x,y,z,p) have to be deleted but the question is how ? I know Mark & Sweep is a garbage collection algorithm and i thought this variables are now my garbage. Function finished its job and it has to return allocated memory to the system.

I tried following, each object holds a mark bit and after creation mark bit is set to 0. When the program pushes an object that is hold by a variable it converts its mark to 1 and no free error occurs because everyone in the program knows it has an owner. So far so good this approach has worked. But if i have a lots of variables like in the example, how can i delete multiple pointers ?

Here my assumption was, first break the ownership between x and its object. Then say every variable to mark their objects (and if the object is a tuple then it sets its objects mark bit to 1, recursively). Now (1,2,...) object's mark bit is set 1 by variable 'a'; I can try to free it but program does not allow. If i make this for every variable in my table, complexity looks like huge (i have mark and sweep phase for every object).

My question is am i misunderstood the Mark & Sweep algorithm ? Are the roots my variables ? How can i delete multiple pointers and even cyclic references ?

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots

No comments: