Alex Rivera | Logout

How to avoid Memory Leaks?

Asked 2009-04-27T17:25:23.427
17

What are some tips I can use to avoid memory leaks in my applications? Are there any gotchas or pitfalls that I can look out for?

Edit
Report

3 Answers

5

I know some people are going to advise garbage collection as the solution. But there are lots of cases where garbage collection doesn't give you the results that you expect. It is easy to end up holding on to a stray reference which prevents whole chains of memory from being freed. Read about how this torpedoed a DARPA Grand Challenge entry. You can argue these aren't memory leaks but if the program expects that memory to be freed it is still a problem. Just like in C programming, after a couple of months you get the hang of how to make sure you don't leave unwanted references behind.

answered 2009-04-27T17:38:10.273
5

Memory leaks are bugs, so in general - the question could be answered the same as "how to code without bugs"? In the long run - it is not possible to have no bugs, but you can limit the chance for having those in the released code.

Start with caring about developed code quality and following the guidelines mentioned by others.

  1. Simplicity is golden - the more simple the code - the less a chance for bugs or leaks
  2. Be careful when using unmanaged resources - Windows Handles, DB connections, GDI objects, etc.
  3. Use using for IDisposables
  4. Implement IDisposable for classes that carry unmanaged resources
  5. Make sure to remove any references to unused objects - including the tricky event handlers

On top of these - implement tests to see if the memory leaks - unit, concurrency, stress and load tests could help here most. See if memory leaks by checking metrics (perf counters). You could also log object creations and destructions and analyze the logs at the end of a test.

answered 2009-04-27T17:53:26.993
2

The most common case of memory not being destroyed by the GC is when you have event handlers that did not get unhooked properly. You can unhook in Dispose() if you want.

I describe the problem more in detail, and I have a way to write tests to determine if you leak the object here.

answered 2009-04-27T17:59:10.457

Your Answer