Exceptions and memory leaks-Collection of common programming errors

What is a “memory leak”? In manually managed environments we say that unreferenced allocations are a leak. By this definition, there are no leaks in a GC environment.

However, there are a few scenarios that have the same effect:

Stale References

// create temporary item
Item item = new Item();

// add it to the global map, so Processor::Fetch finds it by ID
itemMap.Add(item.id, item);
Process(item.id);

// remove from cache
itemMap.Remove(item.id);

If Process() throws, the item remains referenced in itemMap. Unless you regulary throw out the entire map (or you made the wise decision to use weak pointers for the map), the item map will accumulate and hold references to temporaries, blocking memory.

Unmanaged resources

Imagine you have a small managed object that allocates large unmanaged resources, and does not implement IDisposable, or IDisposable isn’t used.

These objects might live long enough to get pushed to Gen 2. If there’s no other pressure on the managed heap, a Gen 2 collection might never run. You may end up pushing tiny objects into Gen 2 until the unmanaged resources exhaust your memory.

This scenario might sound silly, but that’s exactly how COM Interop works (and I have a case ID to prove it).

Originally posted 2013-11-27 12:27:05.