Linked List:
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
public static void Main(){
ListNode head = new ListNode(5);
ListNode curr = head;
curr.next = new ListNode(6);
curr = curr.next;
curr.next = new ListNode(7);
curr = curr.next;
curr.next = new ListNode(8);
curr = null;
}
I created a Linked using above code. head is a ListNode identfier which points to node1 intially. After pointing head to node2, will node1 be collected by garbage collector? Note that node1 is not referenced by any identifier now however it's next pointer in heap memory still points to a non-null object?
CodePudding user response:
Unless its reference is held by another object it will be collected. To test it, you can add a finalizer to the node class (doc here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers)
public class ListNode {
public int val;
public ListNode next;
public ListNode(int val=0, ListNode next=null) {
this.val = val;
this.next = next;
}
~ListNode() // finalizer
{
Console.WriteLine("Hey, I'm being collected!");
}
}
public static void Main(){
ListNode head = new ListNode(5);
ListNode curr = head;
curr.next = new ListNode(6);
curr = curr.next;
curr.next = new ListNode(7);
curr = curr.next;
curr.next = new ListNode(8);
curr = null;
//force the garbage collection
GC.Collect();
GC.WaitForPendingFinalizers();
//look at the standard output
}
CodePudding user response:
Yes, the garbage collector will, when it does a full collection, collect any objects that are no longer referenced. Your node1
would no longer be referenced in your example.
But... In such a simple program the GC will probably never run. In general you rarely need to worry about collecting memory, the main things to worry about regarding memory leaks are:
- If you have some kind of list where you add objects but never remove them, a non intuitive example of this are events, that are internally a list of delegates.
- Disposing any objects implementing
IDisposable
. Not disposing such objects may not lead to memory leaks, but should be done to ensure correct function of your program. (with some notable exceptions, likeTask
) - When dealing with native memory