vote buttons
2
1
beginner
0
intermediate
0
advanced
29-Dec-2014 04:23 UTC
Maverick
12

1 Answers

vote buttons
0
Though .Net has automatic memory management and it does a good job in freeing up objects not in use, there is still a possibility of a memory leak when unwanted references linger around indefinitely or when unmanaged resources are not disposed off. Following are a few examples:

Subscriptions to Event Handlers

Consider the following code:
var shortLivedObject = new ShortLivedObject();
mainForm.SomeEvent += shortLivedObject.HandleSomeEvent;
Now say after a short while shortLivedObject is not needed and is either disposed off or goes out of scope and there are no other variables pointing to this instance. We would then expect the garbage collector to free up the memory allocated for it when it runs. However Garbage Collector is unable to do so as mainForm.SomeEvent still has an active reference to this instance (more specifically the handler which resides in this instance). So it cannot clean it up till the mainForm object is destroyed. We have a leak. 

To avoid this we must unsubscribe to this event (mainForm.SomeEvent -= shortLivedObject.HandleSomeEvent). A better practice is to use weak event pattern. See here for more details.

Unmanaged Memory Leak

In C# you can allocate unmanged memory. If you do so you must free it explicitly or else you will have a memory leak. Garbage Collector can only manage the managed heap.
var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(someObject));
The memory allocated by the above statement will remain allocated throughout the life of the application, unless you call
Marshal.FreeHGlobal(ptr);


Other Instances of Leak


If your object lives longer than expected even after multiple garbage collection cycles, you have a potential memory leak. There could be numerous scenarios of this and would be very specific to the code you are writing. E.g. suppose you are having a static list of objects. If you add an object to this list you must also remove it once it is no longer required. If you forget to remove it, or some exception causes it to be not getting removed from the list, you are introducing a memory leak.

Some people classify not calling the dispose method of an IDisposable object (e.g Streams etc) as introducing a memory leak. These are not exactly memory leaks as when the garbage collector runs it will call dispose and clean up the object. Nevertheless you should always call Dispose() on disposable objects (or use using statement), to avoid performance degradation. 

29-Dec-2014 04:24 UTC
Maverick
12
Related Questions