Reputation: 1902
Say I have the following class that simply allocates an array:
public class ArrayAllocator
{
private int[] _arr;
public int [] Allocate(uint size)
{
_arr = new int[size];
return _arr;
}
}
Which I then use like this:
ArrayAllocator allocator = new ArrayAllocator();
int [] result;
result = allocator.Allocate(10); // create space for 10 ints
result = allocator.Allocate(20); // create space for 20 ints, using the same pointer
Does the GC know that I have finished with the initial 10 ints when I make the next allocation using the same pointer _arr
and free the memory when it runs?
Thanks
Upvotes: 0
Views: 58
Reputation: 6276
When you use the Allocate
function the _arr
is pointing to new location in memory, if there is no live instance which is pointing to your earlier _arr
(memory pointer) then that memory is applicable for GC'ed as no more live references can be found pointing to old memory.
Remember: GC marks the objects applicable for Garbage Collection when no more live references do exist in the program by which that object can be reached.
EDIT So your question
Does the GC know that I have finished with the initial 10 ints when I make the next allocation using the same pointer
_arr
and free the memory when it runs?
has a simple answer, YES it knows that memory pointed by old array, has no more live references pointing to it and it will be marked as Garbage and shortly memory will be recollected.
Upvotes: 2