473,597 Members | 2,156 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory Leak in managed Code

The following code will create memory leaks!!!
using System;
using System.Diagnost ics;
using System.Data;
using System.Data.Sql Client;
namespace MemoryLeak
{
public class RGCSqlConnectio n:System.IDispo sable
{
SqlConnection m_connSQL;
public RGCSqlConnectio n(string dbName, string serverName)
{
string ServerName=serv erName;
string DBName=dbName;
string m_strConn="Conn ection Timeout=45;Inte grated Security=SSPI;P ersist
Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
serverName;
m_connSQL= new SqlConnection(m _strConn);
m_connSQL.Open( );
}
#region IDisposable Members

public void Dispose()
{
m_connSQL.Dispo se();
}

#endregion
}

public class TestClass
{
int [] a=new int [100];
~TestClass()
{
}
[STAThread]
static void Main()
{
RGCSqlConnectio n conn = new RGCSqlConnectio n("Northwind"," localhost");
conn.Dispose();

TestClass t;
do
{
t=new TestClass();
}
while (true);
}
}

}

Dec 23 '05 #1
23 4530
James wrote:
The following code will create memory leaks!!!
using System;
using System.Diagnost ics;
using System.Data;
using System.Data.Sql Client;
namespace MemoryLeak
{
public class RGCSqlConnectio n:System.IDispo sable
{
SqlConnection m_connSQL;
public RGCSqlConnectio n(string dbName, string serverName)
{
string ServerName=serv erName;
string DBName=dbName;
string m_strConn="Conn ection Timeout=45;Inte grated Security=SSPI;P ersist
Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
serverName;
m_connSQL= new SqlConnection(m _strConn);
m_connSQL.Open( );
}
#region IDisposable Members

public void Dispose()
{
m_connSQL.Dispo se();
}

#endregion
}

public class TestClass
{
int [] a=new int [100];
~TestClass()
{
}
[STAThread]
static void Main()
{
RGCSqlConnectio n conn = new RGCSqlConnectio n("Northwind"," localhost");
conn.Dispose();

TestClass t;
do
{
t=new TestClass();
}
while (true);
}
}

}


I don't think that you have an understanding of what a memory leak is.
Calling dispose will just mark the object from Garbage Collection, the
objects will eventially get disposed of, but not right away. To test
for a memory leak, run your app, then close it and see if resources are
returned to the heap.

--
Rob Schieber
Dec 23 '05 #2
I understand what you said.
Please run the code and see if the memory goes up. The memory leak problem
that I talked about happens in the while loop

-James

"Rob Schieber" wrote:
James wrote:
The following code will create memory leaks!!!
using System;
using System.Diagnost ics;
using System.Data;
using System.Data.Sql Client;
namespace MemoryLeak
{
public class RGCSqlConnectio n:System.IDispo sable
{
SqlConnection m_connSQL;
public RGCSqlConnectio n(string dbName, string serverName)
{
string ServerName=serv erName;
string DBName=dbName;
string m_strConn="Conn ection Timeout=45;Inte grated Security=SSPI;P ersist
Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
serverName;
m_connSQL= new SqlConnection(m _strConn);
m_connSQL.Open( );
}
#region IDisposable Members

public void Dispose()
{
m_connSQL.Dispo se();
}

#endregion
}

public class TestClass
{
int [] a=new int [100];
~TestClass()
{
}
[STAThread]
static void Main()
{
RGCSqlConnectio n conn = new RGCSqlConnectio n("Northwind"," localhost");
conn.Dispose();

TestClass t;
do
{
t=new TestClass();
}
while (true);
}
}

}


I don't think that you have an understanding of what a memory leak is.
Calling dispose will just mark the object from Garbage Collection, the
objects will eventially get disposed of, but not right away. To test
for a memory leak, run your app, then close it and see if resources are
returned to the heap.

--
Rob Schieber

Dec 23 '05 #3

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:58******** *************** ***********@mic rosoft.com...
The following code will create memory leaks!!!
using System;
using System.Diagnost ics;
using System.Data;
using System.Data.Sql Client;
namespace MemoryLeak
{
public class RGCSqlConnectio n:System.IDispo sable
{
SqlConnection m_connSQL;
public RGCSqlConnectio n(string dbName, string serverName)
{
string ServerName=serv erName;
string DBName=dbName;
string m_strConn="Conn ection Timeout=45;Inte grated Security=SSPI;P ersist
Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
serverName;
m_connSQL= new SqlConnection(m _strConn);
m_connSQL.Open( );
}
#region IDisposable Members

public void Dispose()
{
m_connSQL.Dispo se();
}

#endregion
}

public class TestClass
{
int [] a=new int [100];
~TestClass()
{
}
[STAThread]
static void Main()
{
RGCSqlConnectio n conn = new RGCSqlConnectio n("Northwind"," localhost");
conn.Dispose();

TestClass t;
do
{
t=new TestClass();
}
while (true);
}
}

}


No it won't, what makes you think that?
Note that you should not implement IDisposable and your TestClass should not
have a destructor (Finalize).

Willy.
Dec 23 '05 #4
That's something that I dont understand.

Why does the destructor make difference?

Change the t to be a Form class, it will cause the memory leak too.

I tried to add (Application.Do event()) which might eventually fixed the
memory leak problem here, but in my case (which is a much larger windows form
class) will still have the memory leak problem. I really dont understand why.
All my code is managed code and only use .NET libary ( No third party libs).
It is supposed not to have memory leaks, isn't it?

-James
"Willy Denoyette [MVP]" wrote:

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:58******** *************** ***********@mic rosoft.com...
The following code will create memory leaks!!!
using System;
using System.Diagnost ics;
using System.Data;
using System.Data.Sql Client;
namespace MemoryLeak
{
public class RGCSqlConnectio n:System.IDispo sable
{
SqlConnection m_connSQL;
public RGCSqlConnectio n(string dbName, string serverName)
{
string ServerName=serv erName;
string DBName=dbName;
string m_strConn="Conn ection Timeout=45;Inte grated Security=SSPI;P ersist
Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
serverName;
m_connSQL= new SqlConnection(m _strConn);
m_connSQL.Open( );
}
#region IDisposable Members

public void Dispose()
{
m_connSQL.Dispo se();
}

#endregion
}

public class TestClass
{
int [] a=new int [100];
~TestClass()
{
}
[STAThread]
static void Main()
{
RGCSqlConnectio n conn = new RGCSqlConnectio n("Northwind"," localhost");
conn.Dispose();

TestClass t;
do
{
t=new TestClass();
}
while (true);
}
}

}


No it won't, what makes you think that?
Note that you should not implement IDisposable and your TestClass should not
have a destructor (Finalize).

Willy.

Dec 23 '05 #5
James,

Memory leaks are possible in .NET and there are examples in the framework.
Memory leaks are usually associated with managed class using unmanaged
resources. However it is not that easy to spot a memory leak in .NET.

You say in the while loop memory consumptions grow. This is normal. It will
grow until the CLR decides to GC the heap. When it will happen well it
depends. It definitiely won't happen with a simple application and alot of
free memory at application's disposal.

When the GC kicks off again the memory consuption may not go down
completely. Objects that have finalizers it takes 2 GC cycles to be
collected it also depends on object generation, etc. Thre are more to that.
SqlConnections are kept in a pool so even if you close a connection the
object stays pooled.

It is not that easy to localize a memory leak. More often memory leaks
happen because programmers keep some hidden and forgotten references to
unused objects than memory leaks due to bugs in the frameworks.
--

Stoitcho Goutsev (100) [C# MVP]

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:85******** *************** ***********@mic rosoft.com...
I understand what you said.
Please run the code and see if the memory goes up. The memory leak problem
that I talked about happens in the while loop

-James

"Rob Schieber" wrote:
James wrote:
> The following code will create memory leaks!!!
>
>
> using System;
> using System.Diagnost ics;
> using System.Data;
> using System.Data.Sql Client;
>
>
> namespace MemoryLeak
> {
> public class RGCSqlConnectio n:System.IDispo sable
> {
> SqlConnection m_connSQL;
> public RGCSqlConnectio n(string dbName, string serverName)
> {
> string ServerName=serv erName;
> string DBName=dbName;
> string m_strConn="Conn ection Timeout=45;Inte grated
> Security=SSPI;P ersist
> Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
> serverName;
> m_connSQL= new SqlConnection(m _strConn);
> m_connSQL.Open( );
> }
> #region IDisposable Members
>
> public void Dispose()
> {
> m_connSQL.Dispo se();
> }
>
> #endregion
> }
>
> public class TestClass
> {
> int [] a=new int [100];
> ~TestClass()
> {
> }
>
>
> [STAThread]
> static void Main()
> {
> RGCSqlConnectio n conn = new RGCSqlConnectio n("Northwind"," localhost");
> conn.Dispose();
>
> TestClass t;
> do
> {
> t=new TestClass();
> }
> while (true);
> }
> }
>
> }
>


I don't think that you have an understanding of what a memory leak is.
Calling dispose will just mark the object from Garbage Collection, the
objects will eventially get disposed of, but not right away. To test
for a memory leak, run your app, then close it and see if resources are
returned to the heap.

--
Rob Schieber

Dec 23 '05 #6

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:58******** *************** ***********@mic rosoft.com...
The following code will create memory leaks!!!


What you understand to be a memory leak is in fact not a memory leak. The
..Net framework gives excess memory allocation to the requesting application
if the system can spare it. Because it is so expensive to allocate more and
more memory, the system is generous when an application asks the system for
some more memory. If the application requests a little bit more (say 1 MB),
the system may give 5 or 10 MB, just so the application doesn't have to
request memory so much.

When the system starts to get low on resources, the application will return
memory back to the system. Here is a test to see a work-around for your
problem. After the loop finishes, look at how much memory your application
is using then minimize the application. Does the memory change? :)

Mythran

Dec 23 '05 #7
Thanks for replying.
I understand the GC will collect the garbic at a certain time indefintely.
However, if you ran the code, you will see the memory is never going down,
which I assume is a memory leak. In my real application, it is a much more
complex windows form, but the main function is exactly what i wrote in the
post.

-James
"Stoitcho Goutsev (100) [C# MVP]" wrote:
James,

Memory leaks are possible in .NET and there are examples in the framework.
Memory leaks are usually associated with managed class using unmanaged
resources. However it is not that easy to spot a memory leak in .NET.

You say in the while loop memory consumptions grow. This is normal. It will
grow until the CLR decides to GC the heap. When it will happen well it
depends. It definitiely won't happen with a simple application and alot of
free memory at application's disposal.

When the GC kicks off again the memory consuption may not go down
completely. Objects that have finalizers it takes 2 GC cycles to be
collected it also depends on object generation, etc. Thre are more to that.
SqlConnections are kept in a pool so even if you close a connection the
object stays pooled.

It is not that easy to localize a memory leak. More often memory leaks
happen because programmers keep some hidden and forgotten references to
unused objects than memory leaks due to bugs in the frameworks.
--

Stoitcho Goutsev (100) [C# MVP]

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:85******** *************** ***********@mic rosoft.com...
I understand what you said.
Please run the code and see if the memory goes up. The memory leak problem
that I talked about happens in the while loop

-James

"Rob Schieber" wrote:
James wrote:
> The following code will create memory leaks!!!
>
>
> using System;
> using System.Diagnost ics;
> using System.Data;
> using System.Data.Sql Client;
>
>
> namespace MemoryLeak
> {
> public class RGCSqlConnectio n:System.IDispo sable
> {
> SqlConnection m_connSQL;
> public RGCSqlConnectio n(string dbName, string serverName)
> {
> string ServerName=serv erName;
> string DBName=dbName;
> string m_strConn="Conn ection Timeout=45;Inte grated
> Security=SSPI;P ersist
> Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
> serverName;
> m_connSQL= new SqlConnection(m _strConn);
> m_connSQL.Open( );
> }
> #region IDisposable Members
>
> public void Dispose()
> {
> m_connSQL.Dispo se();
> }
>
> #endregion
> }
>
> public class TestClass
> {
> int [] a=new int [100];
> ~TestClass()
> {
> }
>
>
> [STAThread]
> static void Main()
> {
> RGCSqlConnectio n conn = new RGCSqlConnectio n("Northwind"," localhost");
> conn.Dispose();
>
> TestClass t;
> do
> {
> t=new TestClass();
> }
> while (true);
> }
> }
>
> }
>

I don't think that you have an understanding of what a memory leak is.
Calling dispose will just mark the object from Garbage Collection, the
objects will eventially get disposed of, but not right away. To test
for a memory leak, run your app, then close it and see if resources are
returned to the heap.

--
Rob Schieber


Dec 23 '05 #8
That's what I was trying to explain the fact that memory grows doesn
ncessary means there is a memory leak.

Your test I see has nothing to do with the Connection class you've created.
Your test is basically a class that upon creation allocates array of 100
intgers.

And in a loop you create isntances of this class - 100 integers every time.
You say that there is a memory leak because everytime you create a new
object of this TestClass the memory consumption grows. Is that correct?

What do you expect to happen? What is the correct behavior? On every loop
you get more memory, why shouldn't memory grow?

BTW, you made it even harder for the GC declaring this empty destructor
(finalizer).
--

Stoitcho Goutsev (100) [C# MVP]

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:04******** *************** ***********@mic rosoft.com...
Thanks for replying.
I understand the GC will collect the garbic at a certain time indefintely.
However, if you ran the code, you will see the memory is never going down,
which I assume is a memory leak. In my real application, it is a much more
complex windows form, but the main function is exactly what i wrote in the
post.

-James
"Stoitcho Goutsev (100) [C# MVP]" wrote:
James,

Memory leaks are possible in .NET and there are examples in the
framework.
Memory leaks are usually associated with managed class using unmanaged
resources. However it is not that easy to spot a memory leak in .NET.

You say in the while loop memory consumptions grow. This is normal. It
will
grow until the CLR decides to GC the heap. When it will happen well it
depends. It definitiely won't happen with a simple application and alot
of
free memory at application's disposal.

When the GC kicks off again the memory consuption may not go down
completely. Objects that have finalizers it takes 2 GC cycles to be
collected it also depends on object generation, etc. Thre are more to
that.
SqlConnections are kept in a pool so even if you close a connection the
object stays pooled.

It is not that easy to localize a memory leak. More often memory leaks
happen because programmers keep some hidden and forgotten references to
unused objects than memory leaks due to bugs in the frameworks.
--

Stoitcho Goutsev (100) [C# MVP]

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:85******** *************** ***********@mic rosoft.com...
>I understand what you said.
> Please run the code and see if the memory goes up. The memory leak
> problem
> that I talked about happens in the while loop
>
> -James
>
> "Rob Schieber" wrote:
>
>> James wrote:
>> > The following code will create memory leaks!!!
>> >
>> >
>> > using System;
>> > using System.Diagnost ics;
>> > using System.Data;
>> > using System.Data.Sql Client;
>> >
>> >
>> > namespace MemoryLeak
>> > {
>> > public class RGCSqlConnectio n:System.IDispo sable
>> > {
>> > SqlConnection m_connSQL;
>> > public RGCSqlConnectio n(string dbName, string serverName)
>> > {
>> > string ServerName=serv erName;
>> > string DBName=dbName;
>> > string m_strConn="Conn ection Timeout=45;Inte grated
>> > Security=SSPI;P ersist
>> > Security Info=False;Init ial Catalog=" + dbName + ";Data Source=" +
>> > serverName;
>> > m_connSQL= new SqlConnection(m _strConn);
>> > m_connSQL.Open( );
>> > }
>> > #region IDisposable Members
>> >
>> > public void Dispose()
>> > {
>> > m_connSQL.Dispo se();
>> > }
>> >
>> > #endregion
>> > }
>> >
>> > public class TestClass
>> > {
>> > int [] a=new int [100];
>> > ~TestClass()
>> > {
>> > }
>> >
>> >
>> > [STAThread]
>> > static void Main()
>> > {
>> > RGCSqlConnectio n conn = new
>> > RGCSqlConnectio n("Northwind"," localhost");
>> > conn.Dispose();
>> >
>> > TestClass t;
>> > do
>> > {
>> > t=new TestClass();
>> > }
>> > while (true);
>> > }
>> > }
>> >
>> > }
>> >
>>
>> I don't think that you have an understanding of what a memory leak is.
>> Calling dispose will just mark the object from Garbage Collection, the
>> objects will eventially get disposed of, but not right away. To test
>> for a memory leak, run your app, then close it and see if resources
>> are
>> returned to the heap.
>>
>> --
>> Rob Schieber
>>


Dec 23 '05 #9

"James" <Ja***@discussi ons.microsoft.c om> wrote in message
news:4C******** *************** ***********@mic rosoft.com...
That's something that I dont understand.

Why does the destructor make difference?

It has nothing to do with your so called memory leak. However, It's not
needed, worse it creates some overhead as each object must be registered as
a finalizable object, so it needs two GC runs before getting collected.

Change the t to be a Form class, it will cause the memory leak too.

I tried to add (Application.Do event()) which might eventually fixed the
memory leak problem here, but in my case (which is a much larger windows
form
class) will still have the memory leak problem. I really dont understand
why.
All my code is managed code and only use .NET libary ( No third party
libs).
It is supposed not to have memory leaks, isn't it?

-James


When I run the code you posted (both on v1.1 4322 SP1 and v2 of the
framework), the "working set" stays the same ~12MB and the private bytes
stay at ~9MB. That means there is no leak at all.
I realy don't know what values you are measuring and what version of the
framework you are running, so it would help us if you post your memory
counter values.
Willy.
Dec 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3267
by: Tom | last post by:
We have a VERY simple .NET C# Form Application, that has about a 23MB Memory Footprint. It starts a window runs a process and does a regular expression. I have done a GC.Collect to make sure that, no memory is lying around. GC reports only 84k of allocations. Starting 5-10 of this apps is going to start taking a considerable amount of memory. Is there a way to reduce this? Tom
0
3894
by: Frank Lopez | last post by:
Does anyone know if Microsoft generated a whitepaper on this topic? Does anyone know what the solution is? (meaning, eliminate the leak problem -- I am seeing three memory leaks from dllmodul.cpp(102) similar to what is mentioned below)... I am calling MFC as part of unmanaged code used by the managed code. +--------
0
2057
by: Frank Lopez | last post by:
My program structure is: 1. 2. 3. => manually does the crt-init and crt-terminate calls 4. -- this is accessed by the unmanaged C++ classes in (3) using LoadLibrary and FreeLibrary
9
425
by: Anton | last post by:
{Willy Skjveland} Hi, how can I trace a Memory leak in aspnet_wp.exe? {Rheena} One moment please while I search it for you. It may take me a few moments {Willy Skjveland} I need to find out which application and which dll and asmx page that cause the problem. {Rheena} May I know what operating system you are using?
3
3749
by: Florin | last post by:
Hi all, I have a problem related to memory grow on a server application which is basically stateless (I have some static info loaded). The client accesses this server using remoting and it has worked for about 2 years without problems. The problem I have encountered lately is that the memory on server side started to grow and not to be released. I have checked first new functionalities but after isolating these on separate server, the...
7
6926
by: Salvador | last post by:
Hi, I am using WMI to gather information about different computers (using win2K and win 2K3), checking common classes and also WMI load balance. My application runs every 1 minute and reports the status of the machines. Upon we follow the .NET object lifetime recommendations the application is constantly consuming more memory! The problem is on the ManagementObjectSearch, upon we Dispose the object it seems that is not releasing the...
30
4675
by: MAG1301 | last post by:
I've detected memory leaks in our huge .NET 1.1 C# application but couldn't localize them directly. So I've reduced the code to the following console application: using System; using System.IO; namespace MemLeak { class MemLeak
22
9326
by: Peter | last post by:
I am using VS2008. I have a Windows Service application which creates Crystal Reports. This is a multi theaded application which can run several reports at one time. My problem - there is a memory leak someplace. I can not detect the memory leak by running several reports by hand, but when I run tha app as a servrice and process few hundred reports there is significant memory leak. The application can consume over 1GB of memory where it...
3
3219
by: not_a_commie | last post by:
The CLR won't garbage collect until it needs to. You should see the memory usage climb for some time before stabilizing. Can you change your declaration to use the 'out' keyword rather than a 'ref' keyword?
0
8272
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8381
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8035
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8258
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5431
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3886
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3927
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2404
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1238
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.