Ignoring unsafe code, .NET cannot have memory leaks. I've read this endlessly from many experts and I believe it. However, I do not understand why this is so.
It is my understanding that the framework itself is written in C++ and C++ is susceptible to memory leaks.
- Is the underlying framework so well-written, that it absolutely does not have any possibility of internal memory leaks?
- Is there something within the framework's code that self-manages and even cures its own would-be memory leaks?
- Is the answer something else that I haven't considered?
Here's an example of a memory leak in .NET, which doesn't involve unsafe/pinvoke and doesn't even involve event handlers.
Suppose you're writing a background service that receives a series of messages over a network and processes them. So you create a class to hold them.
OK, so far so good. Later on you realize that some requirement in the system could sure be made easier if you had a reference to the previous message available when you do the processing. There could be any number of reasons for wanting this.
So you add a new property...
And you write the code to set it. And, of course, somewhere in the main loop you have to have a variable to keep up with the last message:
Then you discover some days later than your service has bombed, because it has filled up all the available memory with a long chain of obsolete messages.
After reviewing Microsoft documentation, specifically "Identifying Memory Leaks in the CLR", Microsoft does make the statement that as long as you are not implementing unsafe code within your application that it is not possible to have a memory leak
Now, they also point out the concept of a perceived memory leak, or as was pointed out in the comments a "resource leak", which is the use of an object that has lingering references and is not disposed of properly. This can happen with IO Objects, DataSets, GUI elements, and the like. They are what I would typically equate to a "memory leak" when working with .NET, but they are not leaks in the traditional sense.
Due to garbage collection, you can't have regular memory leaks (aside from special cases such as unsafe code and P/Invoke). However, you can certainly unintentionally keep a reference alive forever, which effectively leaks memory.
edit
The best example I've seen so far of a genuine leak is the event handler += mistake.
edit
See below for an explanation of the mistake, and of the conditions under which it qualifies as a genuine leak as opposed to an almost-genuine leak.
One major source of C/C++ memory leaks that effectively doesn't exist in .Net is when to deallocate shared memory
The following is from a Brad Abrams led class on Designing .NET Class Libraries
"Well, the first point is, of course, there are no memory leaks, right? No? There are still memory leaks? Well, there is a different kind of memory leak. How about that? So the kind of memory leak that we don’t have is, in the old world, you used to malloc some memory and then forget to do a free or add ref and forget to do a release, or whatever the pair is. And in the new world, the garbage collector ultimately owns all the memory, and the garbage collector will free that stuff when there are no longer any references. But there can still sort of be leaks, right? What are the sort of leaks? Well, if you keep a reference to that object alive, then the garbage collector can’t free that. So lots of times, what happens is you think you’ve gotten rid of that whole graph of objects, but there’s still one guy holding on to it with a reference, and then you’re stuck. The garbage collector can’t free that until you drop all your references to it.
The other one, I think, is a big issue. No memory ownership issue. If you go read the WIN32 API documentation, you’ll see, okay, I allocate this structure first and pass it in and then you populate it, and then I free it. Or do I tell you the size and you allocate it and then I free it later or you know, there are all these debates going on about who owns that memory and where it’s supposed to be freed. And many times, developers just give up on that and say, “Okay, whatever. Well, it’ll be free when the application shuts down,” and that’s not such a good plan.
In our world, the garbage collector owns all the managed memory, so there’s no memory ownership issue, whether you created it and pass it to the application, the application creates and you start using it. There’s no problem with any of that, because there’s no ambiguity. The garbage collector owns it all. "
Full Transcript
You can absolutely have memory leaks in .NET code. Some objects will, in some cases, root themselves (though these are typically
IDisposable
). Failing to callDispose()
on an object in this case will absolutely cause a real, C/C++ style memory leak with an allocated object that you have no way to reference.In some cases, certain timer classes can have this behavior, as one example.
Any case where you have an asynchronous operation that may reschedule itself, you have a potential leak. The async op will typically root the callback object, preventing a collection. During execution, the object is rooted by the executing thread, and then the newly-scheduled operation re-roots the object.
Here's some sample code using
System.Threading.Timer
.Much like GlaDOS, the
Leaker
object will be indefinitely "still alive" - yet, there is no way to access the object (except internally, and how can the object know when it's not referenced anymore?)I suppose it is possible to write software, e.g. the .NET runtime environment (the CLR), that does not leak memory if one is careful enough. But since Microsoft does issue updates to the .NET framework via Windows Update from time to time, I'm fairly sure that there are occasional bugs even in the CLR.
All software can leak memory.
But as others have already pointed out, there are other kinds of memory leaks. While the garbage collector takes care of "classic" memory leaks, there's still, for example, the problem of freeing so-called unmanaged resources (such as database connections, open files, GUI elements, etc.). That's where the
IDisposable
interface comes in.Also, I've recently come across with a possible leaking of memory in a .NET-COM interop setting. COM components use reference counts to decide when they can be freed. .NET adds yet another reference counting mechanism to this which can be influenced via the static
System.Runtime.InteropServices.Marshal
class.After all, you still need to be careful about resource management, even in a .NET program.