Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will I cause a memory leak by assigning new value[] to a filled array

I have an array that works more or less like a hastable: based on an index, a value will be placed in the array, so some indices of the array will have values inside, others might not or will not. I have two pieces of code:

public void register( int index, string value )
{
    _array[index] = value;
}
public void unregisterAll( )
{
    /*
    is this going to cause a memory leak when some of the values
    are filled int the above function?
    */
    _array = new string[12];
}
like image 276
GeekPeek Avatar asked Nov 26 '25 21:11

GeekPeek


1 Answers

C# uses a garbage collector. If an object is no longer referenced it is (after some time) free'd automatically.

This is what happens (from the perspective of the garbage collector (GC)) when you execute unregisterAll()

object_array`1: referenced by _array
// execute unregisterAll();
create object_array`2 and let _array reference it
// Some time later when the GC runs
object_array`1: not referenced
object_array`2: referenced by _array
// Some time later, when the GC decided to collect
collect object__array`1

Note that this doesn't mean you cannot have a memory leak in C#. Some objects use unmanaged resources which need to be disposed manually (they implement the interface IDisposable which you can dispose of automatically by scoping it in a using block:

using(IDisposable disposable = new ...)
{
    // use it
} // when leaving this scope disposable.Dispose() is automatically called

Or which you can dispose of manually by calling Dispose() on them.

like image 184
Roy T. Avatar answered Nov 29 '25 10:11

Roy T.