Best memory-management questions in March 2011

What causes memory fragmentation in .NET

23 votes

I am using Red Gates ANTS memory profiler to debug a memory leak. It keeps warning me that:

Memory Fragmentation may be causing .NET to reserver too much free memory.

or

Memory Fragmentation is affecting the size of the largest object that can be allocated

Because I have OCD, this problem must be resolved.

What are some standard coding practices that help avoid memory fragmentation. Can you defragment it through some .NET methods? Would it even help?

You know, I somewhat doubt the memory profiler here. The memory management system in .NET actually tries to defragment the heap for you by moving around memory (that's why you need to pin memory for it to be shared with an external DLL).

Large memory allocations taken over longer periods of time is prone to more fragmentation. While small ephemeral (short) memory requests are unlikely to cause fragmentation in .NET.

Here's also something worth thinking about. With the current GC of .NET, memory allocated close in time, is typically spaced close together in space. Which is the opposite of fragmentation. i.e. You should allocate memory the way you intend to access it.

Is it a managed code only or does it contains stuff like P/Invoke, unmanaged memory (Marshal.AllocHGlobal) or stuff like GCHandle.Alloc(obj, GCHandleType.Pinned)?

iPhone - Why didn't the Static Analyzer pick this up?

6 votes
@property(nonatomic, retain) NSMutableArray* playerList;

...

team.playerList = [[NSMutableArray alloc] initWithArray:self.playerList];

This is a memory leak right?

So why couldn't the static analysier pick this up?

Yes, that's a memory leak; you need to either autorelease that array or manually release it after setting the property. I'm not sure why the static analyzer missed it—you might consider filing a bug against the developer tools.