- Home /
Does local reference variable memory free as method finish execution ?
as we all know, if a method finish execution, all the local variables memory will be free. so i have a question , if i new a object ,what will happen if the method finish execution ? my code is below.
/// <summary>
/// Free the memory of the new object.
/// </summary>
void FreeMemory()
{
Object temp = new Object();
}
i think the temp 's memory will not be free until GC collect it. because the temp object is in the heap not stack.
If the $$anonymous$$ethod should work properly and is not just for testing purpose it could take a parameter (Object for example) and just set it to null. In C++ you could use delete but as you correctly stated above the GC is in duty to collect unused memory.
as the top code, like you say the temp object 's reference value will be null after the method exit. so i should not assign temp=null before method exit ? just automatic free by stack.
Answer by HarshadK · Jan 06, 2015 at 10:31 AM
The pointer to the Object will no longer be available but the memory allocated to the object will still stay allocated until next garbage collection.
the Object will no longer be available , i can say the temp =null ? so i don't need reassign temp = null after the method exit with the above example code.