Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Leaks in C# WPF

I could use some advice on tracking down the cause of memory leaks in C#. I understand what is a memory leak and I get why they occur in C# but I'm wondering what tools/strategies have you used in the past to resolve them?

I am using .NET Memory Profiler and I've found that one of my huge main objects is staying in memory after I close the window it manages but I'm not sure what to do to severe all links to it.

If I'm not being clear enough just post an answer with a question and I'll edit my question in response. Thanks!

like image 393
Justin Bozonier Avatar asked Oct 22 '08 23:10

Justin Bozonier


People also ask

What causes memory leaks C?

Memory leaks occur when new memory is allocated dynamically and never deallocated. In C programs, new memory is allocated by the malloc or calloc functions, and deallocated by the free function.

What is memory leak give an example?

An example of memory leakThe memory leak would occur if the floor number requested is the same floor that the elevator is on; the condition for releasing the memory would be skipped. Each time this case occurs, more memory is leaked.

What is memory leak in C and why it should be avoided?

How can we avoid? Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.


1 Answers

Break into the debugger and then type this into the Immediate window:

.load C:\Windows\Microsoft.NET\Framework\v2.0.50727\sos.dll 

The path to sos.dll varies. The way to find out the correct path is to look for mscorwks.dll in the Modules pane. Wherever that is loaded from is the correct path for sos.dll.

Then type this:

System.GC.Collect() 

That will ensure anything not reachable is collected. Then type this:

!DumpHeap -type <some-type-name> 

This will show you a table of all existing instances, with addresses. You can find out what is keeping an instance alive like this:

!gcroot <some-address> 
like image 166
Daniel Earwicker Avatar answered Sep 23 '22 00:09

Daniel Earwicker