<p>In .NET perspective:</p>

<ul>
<li>What is a <a href="https://en.wikipedia.org/wiki/Memory_leak" rel="noreferrer">memory leak</a>?</li>
<li>How can you determine whether your application leaks? What are the effects?</li>
<li>How can you prevent a memory leak?</li>
<li>If your application has memory leak, does it go away when the process exits or is killed? Or do memory leaks in your application affect other processes on the system even after process completion?</li>
<li>And what about unmanaged code accessed via COM Interop and/or P/Invoke?</li>
</ul>

[{'answer_id': 107, 'author': 'Bernard', 'author_id': 61, 'author_profile': 'https://Stackoverflow.com/users/61', 'pm_score': 4, 'selected': False, 'text': '<p>I guess in a managed environment, a leak would be you keeping an unnecessary reference to a large chunk of memory around.</p>\n'}, {'answer_id': 110, 'author': 'Pat', 'author_id': 36, 'author_profile': 'https://Stackoverflow.com/users/36', 'pm_score': 3, 'selected': False, 'text': '<p>I will concur with Bernard as to in .net what a mem leak would be.</p>\n\n<p>You could profile your application to see its memory use, and determine that if its managing a lot of memory when it should not be you could say it has a leak.</p>\n\n<p>In managed terms I will put my neck on the line to say it does go away once the process is killed/removed.</p>\n\n<p>Unmanaged code is its own beast and if a leak exists within it, it will follow a standard mem. leak definition.</p>\n'}, {'answer_id': 112, 'author': 'Karl Seguin', 'author_id': 34, 'author_profile': 'https://Stackoverflow.com/users/34', 'pm_score': 8, 'selected': True, 'text': '<p>The best explanation I\'ve seen is in Chapter 7 of the free <a href="http://codebetter.com/karlseguin/2008/06/25/foundations-of-programming-ebook/" rel="noreferrer">Foundations of Programming e-book</a>.</p>\n\n<p>Basically, in <strong>.NET</strong> a memory leak occurs when referenced objects are rooted and thus cannot be garbage collected. This occurs accidentally when you hold on to references beyond the intended scope.</p>\n\n<p>You\'ll know that you have leaks when you start getting OutOfMemoryExceptions or your memory usage goes up beyond what you\'d expect (<strong>PerfMon</strong> has nice memory counters). </p>\n\n<p>Understanding <strong>.NET</strong>\'s memory model is your best way of avoiding it. Specifically, understanding how the garbage collector works and how references work — again, I refer you to chapter 7 of the e-book. Also, be mindful of common pitfalls, probably the most common being events. If object <strong>A</strong> is registered to an event on object <strong>B</strong>, then object <strong>A</strong> will stick around until object <strong>B</strong> disappears because <strong>B</strong> holds a reference to <strong>A</strong>. The solution is to unregister your events when you\'re done. </p>\n\n<p>Of course, a good memory profile will let you see your object graphs and explore the nesting/referencing of your objects to see where references are coming from and what root object is responsible (<a href="http://www.red-gate.com/products/ants_memory_profiler/index.htm" rel="noreferrer">red-gate ants profile</a>, JetBrains dotMemory, <a href="http://memprofiler.com/" rel="noreferrer">memprofiler</a> are really good choices, or you can use the text-only <strong>WinDbg</strong> and <strong>SOS</strong>, but I\'d strongly recommend a commercial/visual product unless you\'re a real guru).</p>\n\n<p>I believe unmanaged code is subject to its typical memory leaks, except that shared references are managed by the garbage collector. I could be wrong about this last point.</p>\n'}, {'answer_id': 159, 'author': 'Coincoin', 'author_id': 42, 'author_profile': 'https://Stackoverflow.com/users/42', 'pm_score': 5, 'selected': False, 'text': '<p>Strictly speaking, a memory leak is consuming memory that is "no longer used" by the program.</p>\n\n<p>"No longer used" has more than one meaning, it could mean "no more reference to it", that is, totally unrecoverable, or it could mean, referenced, recoverable, unused but the program keeps the references anyway. Only the later applies to .Net for <strong>perfectly managed objects</strong>. However, not all classes are perfect and at some point an underlying unmanaged implementation could leak resources permanently for that process.</p>\n\n<p>In all cases, the application consumes more memory than strictly needed. The sides effects, depending on the ammount leaked, could go from none, to slowdown caused by excessive collection, to a series of memory exceptions and finally a fatal error followed by forced process termination.</p>\n\n<p>You know an application has a memory problem when monitoring shows that more and more memory is allocated to your process <strong>after each garbage collection cycle</strong>. In such case, you are either keeping too much in memory, or some underlying unmanaged implementation is leaking.</p>\n\n<p>For most leaks, resources are recovered when the process is terminated, however some resources are not always recovered in some precise cases, GDI cursor handles are notorious for that. Of course, if you have an interprocess communication mechanism, memory allocated in the other process would not be freed until that process frees it or terminates.</p>\n'}, {'answer_id': 161, 'author': 'John', 'author_id': 33, 'author_profile': 'https://Stackoverflow.com/users/33', 'pm_score': 4, 'selected': False, 'text': '<p>I would define memory leaks as an object not freeing up all the memory allocated after it has completed. I have found this can happen in your application if you are using Windows API and COM (i.e. unmanaged code that has a bug in it or is not being managed correctly), in the framework and in third party components. I have also found not tiding up after using certain objects like pens can cause the issue.</p>\n\n<p>I personally have suffered Out of Memory Exceptions which can be caused but are not exclusive to memory leaks in dot net applications. (OOM can also come from pinning see <a href="https://blogs.msdn.com/yunjin/archive/2004/01/27/63642.aspx" rel="noreferrer">Pinning Artical</a>). If you are not getting OOM errors or need to confirm if it is a memory leak causing it then the only way is to profile your application.</p>\n\n<p>I would also try and ensure the following:</p>\n\n<p>a) Everything that implements Idisposable is disposed either using a finally block or the using statement these include brushes, pens etc.(some people argue to set everything to nothing in addition) </p>\n\n<p>b)Anything that has a close method is closed again using finally or the using statement (although I have found using does not always close depending if you declared the object outside the using statement)</p>\n\n<p>c)If you are using unmanaged code/windows API\'s that these are dealt with correctly after. (some have clean up methods to release resources)</p>\n\n<p>Hope this helps.</p>\n'}, {'answer_id': 1263, 'author': 'Josh', 'author_id': 257, 'author_profile': 'https://Stackoverflow.com/users/257', 'pm_score': 3, 'selected': False, 'text': '<p>All memory leaks are resolved by program termination.  </p>\n\n<p>Leak enough memory and the Operating System may decide to resolve the problem on your behalf.</p>\n'}, {'answer_id': 2947, 'author': 'Seibar', 'author_id': 357, 'author_profile': 'https://Stackoverflow.com/users/357', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>I guess in a managed environment, a\n  leak would be you keeping an\n  unnecessary reference to a large chunk\n  of memory around.</p>\n</blockquote>\n\n<p>Absolutely. Also, not using the .Dispose() method on disposable objects when appropriate can cause mem leaks. The easiest way to do it is with a using block because it automatically executes .Dispose() at the end:</p>\n\n<pre><code>StreamReader sr;\nusing(sr = new StreamReader("somefile.txt"))\n{\n    //do some stuff\n}\n</code></pre>\n\n<p>And if you create a class that is using unmanaged objects, if you\'re not implementing IDisposable correctly, you could be causing memory leaks for your class\'s users.</p>\n'}, {'answer_id': 4702, 'author': 'Joel Lucsy', 'author_id': 645, 'author_profile': 'https://Stackoverflow.com/users/645', 'pm_score': 3, 'selected': False, 'text': "<p>Also keep in mind that .NET has two heaps, one being the large object heap. I believe objects of roughly 85k or larger are put on this heap. This heap has a different lifetime rules than the regular heap.</p>\n\n<p>If you are creating large memory structures (Dictionary's or List's) it would prudent to go lookup what the exact rules are.</p>\n\n<p>As far as reclaiming the memory on process termination, unless your running Win98 or it equivalents, everything is released back to the OS on termination. The only exceptions are things that are opened cross-process and another process still has the resource open.</p>\n\n<p>COM Objects can be tricky tho. If you always use the <code>IDispose</code> pattern, you'll be safe. But I've run across a few interop assemblies that implement <code>IDispose</code>. The key here is to call <code>Marshal.ReleaseCOMObject</code> when you're done with it. The COM Objects still use standard COM reference counting.</p>\n"}, {'answer_id': 11766, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 4, 'selected': False, 'text': '<p>If you need to diagnose a memory leak in .NET, check these links:</p>\n\n<p><a href="https://web.archive.org/web/20141203155344/http://msdn.microsoft.com/en-us/magazine/cc163833.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/magazine/cc163833.aspx</a></p>\n\n<p><a href="https://web.archive.org/web/20150102222036/http://msdn.microsoft.com/en-us/magazine/cc164138.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/magazine/cc164138.aspx</a></p>\n\n<p>Those articles describe how to create a memory dump of your process and how to analyze it so that you can first determine if your leak is unmanaged or managed, and if it is managed, how to figure out where it is coming from.</p>\n\n<p>Microsoft also has a newer tool to assist with generating crash dumps, to replace ADPlus, called DebugDiag.</p>\n\n<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&amp;displaylang=en" rel="noreferrer">http://www.microsoft.com/downloads/details.aspx?FamilyID=28bd5941-c458-46f1-b24d-f60151d875a3&amp;displaylang=en</a></p>\n'}, {'answer_id': 12433, 'author': 'Martin', 'author_id': 1529, 'author_profile': 'https://Stackoverflow.com/users/1529', 'pm_score': 5, 'selected': False, 'text': '<p>I think the "what is a memory leak" and "what are the effects" questions have been answered well already, but I wanted to add a few more things on the other questions...</p>\n\n<p><strong>How to understand whether your application leaks</strong></p>\n\n<p>One interesting way is to open <em>perfmon</em> and add traces for <em># bytes in all heaps</em> and <em># Gen 2 collections</em> , in each case looking just at your process.  If exercising a particular feature causes the total bytes to increase, and that memory remains allocated after the next Gen 2 collection, you might say that the feature leaks memory.</p>\n\n<p><strong>How to prevent</strong></p>\n\n<p>Other good opinions have been given.  I would just add that perhaps the <em>most commonly overlooked</em> cause of .NET memory leaks is to add event handlers to objects without removing them.  An event handler attached to an object is a form of reference to that object, so will prevent collection even after all other references have gone.  Always remember to detach event handlers (using the <code>-=</code> syntax in C#).</p>\n\n<p><strong>Does the leak go away when the process exits, and what about COM interop?</strong></p>\n\n<p>When your process exits, all memory mapped into its address space is reclaimed by the OS, including any COM objects served from DLLs.  Comparatively rarely, COM objects can be served from separate processes.  In this case, when your process exits, you may still be responsible for memory allocated in any COM server processes that you used.</p>\n'}, {'answer_id': 13312, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 4, 'selected': False, 'text': '<p>Using CLR Profiler from Microsoft <a href="http://www.microsoft.com/downloads/details.aspx?familyid=86ce6052-d7f4-4aeb-9b7a-94635beebdda&amp;displaylang=en" rel="noreferrer">http://www.microsoft.com/downloads/details.aspx?familyid=86ce6052-d7f4-4aeb-9b7a-94635beebdda&amp;displaylang=en</a> is a great way to determine which objects are holding memory, what execution flow leads to the creation of these objects, and also monitoring which objects live where on the heap (fragmentation, LOH, etc.).</p>\n'}, {'answer_id': 18543, 'author': 'Lars Truijens', 'author_id': 1242, 'author_profile': 'https://Stackoverflow.com/users/1242', 'pm_score': 3, 'selected': False, 'text': '<p>I found <a href="http://memprofiler.com/" rel="noreferrer">.Net Memory Profiler</a> a very good help when finding memory leaks in .Net. It\'s not free like the Microsoft CLR Profiler, but is faster and more to the point in my opinion. A</p>\n'}, {'answer_id': 30227, 'author': 'Gus Paul', 'author_id': 3237, 'author_profile': 'https://Stackoverflow.com/users/3237', 'pm_score': 4, 'selected': False, 'text': '<p>The best explanation of how the garbage collector works is in Jeff Richters <a href="https://www.microsoftpressstore.com/store/clr-via-c-sharp-9780735667457" rel="noreferrer">CLR via C#</a> book, (Ch. 20).  Reading this gives a great grounding for understanding how objects persist.</p>\n\n<p>One of the most common causes of rooting objects accidentally is by hooking up events outisde a class.  If you hook up an external event </p>\n\n<p>e.g.</p>\n\n<pre><code>SomeExternalClass.Changed += new EventHandler(HandleIt);\n</code></pre>\n\n<p>and forget to unhook to it when you dispose, then SomeExternalClass has a ref to your class.</p>\n\n<p>As mentioned above, the <a href="http://memprofiler.com" rel="noreferrer">SciTech memory profiler</a> is excellent at showing you roots of objects you suspect are leaking.  </p>\n\n<p>But there is also a very quick way to check a particular type is just use WnDBG (you can even use this in the VS.NET immediate window while attached):</p>\n\n<pre><code>.loadby sos mscorwks\n!dumpheap -stat -type &lt;TypeName&gt;\n</code></pre>\n\n<p>Now do something that you think will dispose the objects of that type (e.g. close a window).  It\'s handy here to have a debug button somewhere that will run <code>System.GC.Collect()</code> a couple of times.</p>\n\n<p>Then run <code>!dumpheap -stat -type &lt;TypeName&gt;</code> again.  If the number didn\'t go down, or didn\'t go down as much as you expect, then you have a basis for further investigation.\n(I got this tip from a seminar given by <a href="http://www.thinktecture.com/staff/ingo" rel="noreferrer">Ingo Rammer</a>).</p>\n'}, {'answer_id': 37850, 'author': 'neslekkiM', 'author_id': 3308, 'author_profile': 'https://Stackoverflow.com/users/3308', 'pm_score': 4, 'selected': False, 'text': "<p>Why do people think that an memory leak in .NET is not the same as any other leak?</p>\n\n<p>A memory leak is when you attach to a resource and do not let it go. You can do this both in managed and in unmanaged coding.</p>\n\n<p>Regarding .NET, and other programming tools, there have been ideas about garbage collecting, and other ways of minimizing situations that will make your application leak.\nBut the best method of preventing memory leaks is that you need to understand your underlying memory model, and how things works, on the platform you are using.</p>\n\n<p>Believing that GC and other magic will clean up your mess is the short way to memory leaks, and will be difficult to find later.</p>\n\n<p>When coding unmanaged, you normally make sure to clean up, you know that the resources you take hold of, will be your responsibility to clean up, not the janitor's.</p>\n\n<p>In .NET on the other hand, a lot of people think that the GC will clean up everything. Well, it does some for you, but you need to make sure that it is so. .NET does wrap lots of things, so you do not always know if you are dealing with a managed or unmanaged resource, and you need to make sure what what you're dealing with.  Handling fonts, GDI resources, active directory, databases etc is typically things you need to look out for.</p>\n\n<blockquote>\n  <p>In managed terms I will put my neck on\n  the line to say it does go away once\n  the process is killed/removed.</p>\n</blockquote>\n\n<p>I see lots of people have this though, and I really hope this will end. You cannot ask the user to terminate your app to clean up your mess!\nTake a look at a browser, that can be IE, FF etc, then open, say, Google Reader, let it stay for some days, and look at what happens. </p>\n\n<p>If you then open another tab in the browser, surf to some site, then close the tab that hosted the other page that made the browser leak, do you think the browser will release the memory? Not so with IE.  On my computer IE will easily eat 1 GiB of memory in a short amount of time (about 3-4 days) if I use Google Reader. Some newspages are even worse.</p>\n"}, {'answer_id': 25531072, 'author': 'hemant', 'author_id': 3345422, 'author_profile': 'https://Stackoverflow.com/users/3345422', 'pm_score': 1, 'selected': False, 'text': '<p>One definition is: <strong>Unable  to release unreachable memory, which can no longer be allocated to new  process during execution of allocating process. It can mostly be cured by using GC techniques or detected by automated tools.</strong></p>\n\n<p>For more information, please visit <a href="http://all-about-java-and-weblogic-server.blogspot.in/2014/01/what-is-memory-leak-in-java.html" rel="nofollow">http://all-about-java-and-weblogic-server.blogspot.in/2014/01/what-is-memory-leak-in-java.html</a>.</p>\n'}]
['https://Stackoverflow.com/questions/104', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39/']