Why does .NET have no memory leaks?

By ignoring unsafe code, .NET cannot have memory leaks. I read it endlessly from many experts, and I believe it. However, I do not understand why this is so.

I understand that the structure itself is written in C ++, and C ++ is susceptible to memory leaks.

  • Is the underlying structure so well-written that it has absolutely no way of leaking internal memory?
  • Is there something within the framework code that independently manages and even cures its own potential memory leaks?
  • Is the answer different that I have not considered?
+57
memory-leaks
Mar 26 '10 at 19:17
source share
16 answers

There are already good answers here, but I want to turn to another question. Let's look very closely at your specific question:




I understand that the structure itself is written in C ++, and C ++ is susceptible to memory leaks.

  • Is the underlying structure so well-written that it has absolutely no way of leaking internal memory?
  • Is there something within the framework code that independently manages and even cures its own potential memory leaks?
  • Is the answer different that I have not considered?



The key here is to distinguish between your code and code. The .Net interface (and Java, Go, python and other garbage collectors) promise that if you rely on your code, your code will not leak memory ... at least in the traditional sense. You may find yourself in situations where some objects are not freed, as you expect, but these cases are subtly different from traditional memory leaks, since objects are still available in your program.

You are confused because you correctly understand that this is not the same as saying that any program you create cannot have a traditional memory leak. There may still be an error in their code that is a memory leak.

So now you have to ask yourself: do you trust your code or their code? Keep in mind that their code is not only tested by original developers (like yours, right?), It is also fierce from the daily use by thousands (possibly millions) of other programmers like you. Any significant memory leak problems would be among the first to be identified and fixed. Again, I am not saying that this is impossible. It's simply, as a rule, better to rely on your own code than on your own ... at least in this regard.

So the correct answer here is that this is a variant of your first sentence:

Is the underlying structure so well-written that it has absolutely no way of leaking internal memory?

This does not mean that there is no possibility, but it is much safer than managing it yourself. Of course, I do not know any known leaks in the framework.

+43
Mar 27 '10 at 3:27
source share

.NET may have memory leaks.

Basically, people refer to the garbage collector, which decides when to get rid of the object (or the entire cycle of the object). This avoids memory leaks of the classical type c and C ++, so I mean allocating memory and then freeing it.

However, many times, programmers do not realize that objects still have dangling links and do not receive garbage collection, causing a memory leak.

This usually happens when events are logged (with += ), but are not logged later, but also when accessing unmanaged code (using pInvokes or objects that use basic system resources, for example, connecting a file system or database) and not having appropriately resources.

+94
Mar 26 '10 at 19:19
source share

After looking at Microsoft documentation, in particular, “Identifying Memory Leaks in the CLR Environment, ” Microsoft makes an expression that, as long as you are not injecting unsafe code into your application, so that there is no memory leak

Now they also point to the concept of perceived memory leak or, as pointed out in the comments, a “resource leak”, which is a use of an object that has long references and is not disposed of properly. This can happen with IO objects, datasets, GUI elements, etc. This is what I usually equate to a "memory leak" when working with .NET, but they are not leaks in the traditional sense.

+15
Mar 26 '10 at 19:22
source share

Due to garbage collection, you cannot have regular memory leaks (other than special cases such as unsafe code and P / Invoke). However, you can inadvertently keep the link permanently, which effectively leaks memory.

change

The best example I've seen so far is the event handler + = error.

change

See below for an explanation of the error and the conditions under which it qualifies as a real leak, rather than an almost real leak.

+12
Mar 26 '10 at 19:22
source share

Here is an example of a memory leak in .NET that does not include unsafe / pinvoke and even does not include event handlers.

Suppose you are writing a background service that receives a series of messages over a network and processes them. Thus, you create a class to store them.

 class Message { public Message(int id, string text) { MessageId = id; Text = text; } public int MessageId { get; private set; } public string Text { get; private set; } } 

Ok, so far so good. Later, you understand that some requirements in the system can be simplified if you have a link to a previous message that is available during processing. There could be any number of reasons for this.

So you are adding a new property ...

 class Message { ... public Message PreviousMessage { get; private set; } ... } 

And you write the code to install it. And, of course, somewhere in the main loop you should have a variable in order to keep up with the last message:

  Message lastMessageReceived; 

Then you will discover a few days later than your service was bombed, as it filled all available memory with a long chain of outdated messages.

+4
Mar 26 '10 at 19:40
source share

Here are other memory leaks this guy found using the ANTS.NET Profiler: http://www.simple-talk.com/dotnet/.net-tools/tracing-memory-leaks-in-.net-applications-with- ants-profiler /

+4
Mar 31 '10 at 15:19
source share

I suppose you can write software, for example. .NET runtime (CLR) that does not leak memory if you are careful enough. But since Microsoft occasionally releases .NET Framework updates through Windows Update, I am sure that errors sometimes appear in the CLR.

All software can leak memory.

But, as others have already noted, there are other types of memory leaks. While the garbage collector takes care of “classic” memory leaks, there is, for example, the problem of freeing up so-called unmanaged resources (such as database connections, open files, GUI elements, etc.) What happens with the IDisposable interface.

In addition, I recently encountered a possible memory leak in configuring the .NET-COM interop . COM components use reference counting to decide when they can be released..NET adds another reference counting mechanism that can be influenced by the static class System.Runtime.InteropServices.Marshal .

In the end, you still need to be careful in managing resources, even in a .NET program.

+3
Mar 26 '10 at 19:29
source share

You may have memory leak problems in .NET code. Some objects, in some cases, are themselves root (although this is usually IDisposable ). Failure to call Dispose() on an object in this case will absolutely cause a real C / C ++ style memory leak with a allocated object that you do not have for reference.

In some cases, some timer classes may have behavior such as one example.

In any case, when you have an asynchronous operation that can carry itself, you have a potential leak. Async op typically runs the callback object, preventing collection. At run time, the object is bound by the execution thread, and then the newly assigned operation returns the root object.

Here is sample code using System.Threading.Timer .

 public class Test { static public int Main(string[] args) { MakeFoo(); GC.Collect(); GC.Collect(); GC.Collect(); System.Console.ReadKey(); return 0; } private static void MakeFoo() { Leaker l = new Leaker(); } } internal class Leaker { private Timer t; public Leaker() { t = new Timer(callback); t.Change(1000, 0); } private void callback(object state) { System.Console.WriteLine("Still alive!"); t.Change(1000, 0); } } 

Much like GlaDOS , a Leaker object will be infinitely "still alive", but there is no access path for the object (except for the internal one, and how can the object know when it is no longer referenced?)

+2
Mar 27 '10 at 3:00
source share

Well, .NET has a garbage collector to clean things up when it sees fit. This is what separates it from other unmanageable languages.

But .NET may have memory leaks. GDI leaks , for example, are common among Windows Forms applications. One of the applications that I helped to regularly develop the experience. And when office workers use multiple instances all day, it's not uncommon for them to hit the 10,000 Windows GDI object limitations.

+1
Mar 26 '10 at 19:24
source share

If you do not access applications using .NET that discuss these answers very well, but actually refer to the runtime itself, then this can technically have memory leaks, but at the moment the garbage collector implementation is probably almost error free. I heard about one case where an error was detected when something in the runtime, or perhaps only in standard libraries, had a memory leak. But I don’t remember what it was (something very obscure), and I don’t think I can find it again.

+1
Mar 26 '10 at 19:26
source share

One of the main sources of C / C ++ memory leaks that does not actually exist in .NET is to free shared memory

The following is a class led by the Brad Abrams class for designing .NET class libraries.

"Well, first of all, of course, there are no memory leaks, right? No? Are there any more memory leaks? Well, there is another type of memory leak. How about this? A leak that we don’t have, in the old world you used some memory for malloc and then you forgot to make a free one or add ref and forget to make a release, or whatever the couple is in. And in the new world, the garbage collector ultimately owns all the memory, and the garbage collector frees this stuff when there are no more links. But all there may still be leaks, right? What are the leaks? Well, if you keep the link and this object is alive, then the garbage collector cannot free it. So many times what happens, you think that you got rid of all this graph of objects, but still one guy is holding on to him with a link, and then you are stuck. can free this until you drop all your links to it.

Another, I think, a big question. Lack of memory problems. If you read the WIN32 API documentation, you will see, well, I first distribute this structure and pass it in, and then you populate it, and then I release it. Either I tell you the size, and you distribute it, and then I release it later or you know, all this debate is about who owns this memory and where it is supposed to be freed. And many times, developers simply refuse it and say: “Well, anything. Well, it will be free when the application shuts down,” and this is not such a good plan.

In our world, the garbage collector owns all the managed memory, so the problem of owning the memory, whether it was created and transferred to the application, the application creates and starts to use it. There is no problem with this because they have no ambiguity. The garbage collector owns all this. "

Complete transcription

+1
Aug 03 2018-10-10T00:
source share

Remember that the difference between cache and memory leak is politics. If your cache has a bad policy (or, worse, no) to delete objects, it is indistinguishable from a memory leak.

+1
Aug 03 '10 at 16:23
source share

This link shows how leaks can occur in .Net using weak event patterns. http://msdn.microsoft.com/en-us/library/aa970850.aspx

+1
Mar 31 2018-12-12T00:
source share

.NET may have memory leaks, but it does a lot to help you avoid them. All objects of the reference type are allocated from the managed heap, which keeps track of which objects are currently in use (value types are usually allocated on the stack). Whenever a new object of reference type is created in .NET, it stands out from this managed heap. The garbage collector is responsible for periodically starting and releasing any object that is no longer in use (no longer refers to anything else in the application).

Jeffrey Richter’s CLR book through C # contains a good chapter on how memory is managed in .NET.

0
Mar 26 '10 at 19:22
source share

The best example I found was actually with Java, but the same principle applies to C #.

We read text files, which consisted of many long lines (each line was several MB in a heap). From each file, we looked for several substrings of keys and contained only substrings. After processing several hundred text files, we ran out of memory.

It turned out that string.substring (...) will keep the link to the original long string ... although we only saved 1000 characters or so, these substrings will still use several MB of memory. In fact, we saved the contents of each file in memory.

This is an example of broken links that caused a memory leak. The substring method tried to reuse objects, but ended up losing memory.

Edit: not sure if this particular problem is infecting .NET. The idea was to illustrate the actual design / optimization done in the garbage collection language, which in most cases was intelligent and useful, but could lead to unwanted memory usage.

0
Mar 26 '10 at 19:42
source share

And if you use a managed dll, but dll contians unsafe code? I know this is a hair split, but if you don’t have the source code, then from your point of view you only use managed code, but you can still flow.

0
Apr 14 '10 at 2:05 p.m.
source share



All Articles