Please explain the memory leak in the managed code with an example?

I was asked this question in an interview: how does a memory leak problem occur in C # since everyone knows that the garbage collector is responsible for all the memory management work? So how is this possible?

+4
source share
5 answers

From MSDN : -

A memory leak occurs when memory is allocated in a program and never returned to the operating system, even if the program does not use memory anymore. The four main types of memory leaks are listed below:

  • : . . , , .
  • : , , . , . , .
  • : , . , , , .
  • : , . .
 Dim DS As DataSet
  Dim cn As New SqlClient.SqlConnection("data source=localhost;initial catalog=Northwind;integrated security=SSPI")
  cn.Open()

  Dim da As New SqlClient.SqlDataAdapter("Select * from Employees", cn)
  Dim i As Integer
  DS = New DataSet()

  For i = 0 To 1000
      da.Fill(DS, "Table" + i.ToString)
  Next

, , (, DataSet), , , ​​ , , , , , , .

: -

.NET , , , . , , GC .

+2

, , - . , , , AppDomain, . , , OOM. .

. , , , . #, . , -, .

.

+2

- Child, ClickEventHandler, ClickEvent Parent.

GC Child , Parent . Child , GC , Parent


, (Event), GC , .

,

Broadcaster(ClickEvent) -> Subscribers(ClickEventHandler)

GC ClickEventHandlers , ClickEvent !

+1

:

Popups [] collectionOfPopups. .

, , GC .

, GC http://msdn.microsoft.com/en-us/library/ee787088.aspx

.

0

There may be several reasons, but here is one of them:

Consider two classes:

class A
{
  private B b;
}

class B
{
  private A a;
}

If you create an object for each of these classes and cross them, and after that both of these objects go out of scope, you will still have a link to each of them in the other. The GC is very difficult to catch these kinds of cross-references, and it may continue to believe that both objects are still in use.

0
source

All Articles