Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Leak in C#

Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose are disposed?

Would there be cases where some variables are left out?

like image 366
Joan Venge Avatar asked Mar 06 '09 22:03

Joan Venge


People also ask

What is the memory leak in C?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

Why does memory leak occur in C++?

Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator.

What is memory leak give an example?

An example of memory leakThe memory leak would occur if the floor number requested is the same floor that the elevator is on; the condition for releasing the memory would be skipped. Each time this case occurs, more memory is leaked.


1 Answers

Event Handlers are a very common source of non-obvious memory leaks. If you subscribe to an event on object1 from object2, then do object2.Dispose() and pretend it doesn't exist (and drop out all references from your code), there is an implicit reference in object1's event that will prevent object2 from being garbage collected.

MyType object2 = new MyType();  // ... object1.SomeEvent += object2.myEventHandler; // ...  // Should call this // object1.SomeEvent -= object2.myEventHandler;  object2.Dispose(); 

This is a common case of a leak - forgetting to easily unsubscribe from events. Of course, if object1 gets collected, object2 will get collected as well, but not until then.

like image 100
Reed Copsey Avatar answered Oct 05 '22 06:10

Reed Copsey