Are memory leaks possible in managed environments like .NET?

后端 未结 7 1299
梦谈多话
梦谈多话 2021-01-05 02:58

In C++ it is easily possible to have a permanent memory leak - just allocate memory and don\'t release it:

new char; //permanent memory leak guaranteed
         


        
7条回答
  •  庸人自扰
    2021-01-05 03:23

    It depends on how you define a memory leak. In an unmanaged language, we typically think of a memory leak as a situation where memory has been allocated, and no references to it exist, so we are unable to free it.

    That kind of leaks are pretty much impossible to create in .NET (unless you call out into unmanaged code, or unless there's a bug in the runtime).

    However, you can get another "weaker" form of leaks: when a reference to the memory does exist (so it is still possible to find and reset the reference, allowing the GC to free the memory normally), but you thought it didn't, so you assumed the object being referenced would get GC'ed. That can easily lead to unbounded growth in memory consumption, as you're piling up references to objects that are no longer used, but which can't be garbage collected because they're still referenced somewhere in your app.

    So what is typically considered a memory leak in .NET is simply a situation where you forgot that you have a reference to an object (for example because you failed to unsubscribe from an event). But the reference exists, and if you remember about it, you can clear it and the leak will go away.

提交回复
热议问题