Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a memory leak in C# or VB.Net

Inspired from this question, was wondering what are the possible ways to create a memory leak in .Net. I once found one with ODBC Data Access. Has anyone had any experiences with latest version?

Edit: Are there any seemingly normal, harmless uses that can cause memory leaks?

like image 235
Mrchief Avatar asked Jan 19 '23 08:01

Mrchief


1 Answers

The easiest way to create a memory leak is to misuse facilities designed for interop, since they deal with unmanaged memory.

For example, allocate a GCHandle pointing to an object, and never free it.

Edit: Are there any seemingly normal, harmless uses that can cause memory leaks?

Only one that I know of, particularly in some UI programs. It was possible in WinForms, but only recently became common due to WPF with MVVM:

The key point that many people overlook is that a delegate contains a reference to the object on which it runs.

So, if one is using a pattern such as MVVM with two-way bindings (implemented using events, comprised of delegates), and if the View is changed to a different View with the same ViewModel, by default the ViewModel's updates remain bound to both Views, which causes a leak of the old View.

This can in theory happen with any delegate, but in practice it's not common because the subscriber normally outlives the publisher or unsubscribes.

A similar situation exists when lambda event handlers are unsubscribed:

timer.Elapsed += (_, __) => myObj.Notify();
timer.Elapsed -= (_, __) => myObj.Notify();

In this case, even though the lambda expressions are identical, they represent different handlers, so the Elapsed event will still invoke Notify. The second line above has no effect; it doesn't unsubscribe, nor does it raise an error.

Note that improper unsubscriptions are usually caught during testing, so they seldomly cause "leaks" in released code. In contrast, the MVVM situation above causes no observable side effects (other than a memory and resource leak).

like image 164
Stephen Cleary Avatar answered Jan 28 '23 17:01

Stephen Cleary