Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

B. Add one statement to the code to resolve the memory leak in reference countin

ID: 3700787 • Letter: B

Question

B. Add one statement to the code to resolve the memory leak in reference counting.

C. Could this memory leak be avoided if the mark-sweep algorithm is used? Why? 4. The following Java code fragment creates some Node objects and later relinquishes its reference to the objects. class Node ( //Node class definition Node next; /I create Node objects Node p new Node(); p.next new Node); ?.next.next new Node(); p.next.next.next p; // other statements... // relinquish reference to the objects p null; (a) Explain why this code may cause a memory leak if the standard Reference Counting algorithm is used for garbage collection.

Explanation / Answer

A. Above code seems create cyclic reference. Because every node type object created is referencing to the very next node object and finally the last one is again pointing to the root object . So, once it relinquishes it's reference to the objects i.e become unreachable from a root and then those are candidates for collection . As we know reference counting will not detect garbage for cyclic reference , there are chances for memory leak.

B. System.gc(); // we can request JVM to run garbage collector

C. Yes, it is possible to avoid memory leak if mark-sweep algorithm is applied.

In Marrk-Sweep algorithm there are basically two step.

Mark : Once any object is created , it's mark bit is set to zero(false).Now simply performing a graph traversal , it goes to all reachable objects from roots and mark those bit as one(true).

Seep : In this phase it clears from heap memory for all the unreachable and rechable objects whose mark bit is false . Again we run the algorithm to find the reachable objects from root and mark it accordingly.

So, it's pretty clear that even in case of cyclic refence ,this algorithm will not end up in an infinite loop. We can say that it is an good option to handle cyclic refence in order to avoid memory leak .