简体   繁体   中英

Want to understand how a managed language like C# has memory leaks

Since C# is a managed language that performs garbage collection automatically to clean up objects etc, ...

what are the ways one can introduce a memory leak ?

Are there some non-obvious ways that one should look out for?

How can you detect or look for memory leaks (once you understand how they are generated etc.)

Usually leaks show up in the form of a developer writing code that "holds on" to objects when they shouldn't be, which subsequently disallows the garbage collector from collecting on those objects.

The garbage collector is pretty good at what it does, but if you don't understand what it's doing, the likelihood of you introducing memory issues into your program is pretty high.

I would suggest reading up on the GC and understanding how it works.

Here's something to get you started:

http://www.simple-talk.com/dotnet/.net-framework/understanding-garbage-collection-in-.net/

Two.

  • First, building up referenced objects. Like creating objects that subscribe to an event on a form. The form is active, so can not be collected, and the event subscriptions... keep the objects alive.
  • Second, block the garbage colelctor in native code. Like the oracle ODP.NET driever does under certain conditions. Stops the finalizer, so any object requiring finalization WILL NOT GET IT - and thus never be released.

The obvious "memory leak" one could cause in a GC-ed language would be caused simply be retaining a reference to an object after it's needed - this is especially likely if you roll your own caching or keep other global state.

Another way would be leaking memory in unmanaged resources that weren't disposed of, although most of the standard library classes will probably dispose of those in destructors so the memory will be reclaimed sooner or later.

(I'm marking the post as CW because of the open-ended nature of the question.)

A memory leak means keeping in memory objects you don't need anymore. In C#, considering the GC collects unreferenced objects, it's equivalent to say keeping references to objects you don't need. Think about uncorrectly scoped declarations, infinite recursion or iteration...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM