Question

Reassigning to var deallocates it?

Asked by: brettr

if I do this:

SomeClass myobject = new SomeClass();

on a button click and click the button three times, will that create a memory leak?  Meaning, if the new object causes memory to increase by 5k, will I see a 15k memory increase or is that space just reused, resulting in a 5k increase overall?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-05 at 18:34:21ID24876843
Topics

.NET

,

C# Programming Language

,

Programming for ASP.NET

Participating Experts
3
Points
500
Comments
7

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Memory leak
    Hi, Does this piece of code give rise to a memory leak. int *p = malloc( 100 ); p++; p++; free(p); Regards Shayad
  2. Memmory Leaks
    i'm Given With a Service in C++ and have been asked to find the memmory leaks.What should be my approach.Do we have any tools to check for memmory leaks.
  3. DeAllocating memory from STL vector
    A couple questions about vectors: 1) what's the best way to get multi-dimensional vectors? The way I've set it up is (for example): vector <string> string_vec; vector < vector<string> > myvec; for (int i=0; i < 100; i++) { string_vec.push_back(&qu...
  4. Dynamic Memory Allocation/Deallocation
    I have a fairly elusive memory problem. I basically have a windows GUI front-end with a second worker-thread doing some heavy-duty number crunching on the background. I have to allocate quite a lot of dynamic arrays necessary for both number crunching and GUI. Some of those a...
  5. STL deallocate()
    i have a problem in testing STL deallocate() function . ptr=allocate( size,0); memset(ptr,14,size); deallocate(ptr); this should deallocate memory simmilar to delete and free function. i want to test whther the memory is deallocated properly or not. so i fiiled the memory...
  6. Memory leak
    Hello, I have an VC6.0 dll that appears to have a memory leak. This leak is reported to my by Memory Validator. Underneath a sniplet of code: CComPtr<ADODB::_Recordset> rs(cmd->Execute(NULL, NULL, ADODB::adCmdStoredProc)); while (!rs->EndOfFile) { std::wstrin...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: expertsoulPosted on 2009-11-05 at 19:28:45ID: 25756389

Every time you use 'new' keyword a new object is created and memory is allocated for that object.

In this case if you hit button 3 times, 3 instances of SomeClass will be created. The object will be disposed only when Garbage Collector kicks in.

 

by: philipjonathanPosted on 2009-11-05 at 19:42:13ID: 25756446

There are several things to note:

First, objects are automatically garbage-collected. This means, when you click the button the second time, a second SomeClass object will be created, while the first SomeClass object gets ready to be GC-ed. However, GC does not occur immediately. The GC runs on certain intervals (determined by the framework). So, between the time you create the 2nd object (and releasing the 1st one), until the 1st object gets GC-ed, you will see temporary increase of memory usage. However, once the GC runs, the memory usage will go down again.

Second, objects that holds system resources, or unmanaged memory space, must be disposed of immediately after they are out of use. Because, although the object will eventually release system resource or unmanaged memory space that it uses when it gets GC-ed, the GC does not occur immediately. So the object might lockdown certain shared resources, eg. database connection, file handle, etc. Such class typically implements IDisposable, so you can just call it's Dispose method once you are done with it. If you design your own class that uses system resources or unmanaged memory, be sure to implement IDisposable and release those resources in the Dispose method.

Example:

SomeClass myObject = new SomeClass();
// perform operation
myObject.Dispose();

Or, safer still, use C# using syntax:

using (SomeClass myObject = new SomeClass())
{
  // perform operation
}  // <-- myObject.Dispose() will be called automatically here.

 

by: InternalStaticPosted on 2009-11-05 at 20:21:53ID: 25756597

Memory useage in a programming environment like .NET is very complex under the hood, while it's extremely simplified for the developers. We refer to the time an object resides in memory as an object's "lifetime".
 
The post above this one is correct (mostly), though I think such a topic deserves a little more detail.
 
C# is what we call a garbage collected language, much like Java or Python. This means that when we develop in .NET, memory is managed for us. The thing is, how does the application know when to 'destroy' an object, and when to keep it in memory? Simple: every object you create maintains what's called a reference count, which is just a count as to "how many" references there are to a single object. The GC (garbage collector) will run whenever it "feels like it" (by feels like it, I mean the system it uses is way out of the scope of this post), and there's really no way we can predict when this will happen. When the GC does one of these "runs", it looks through the current objects allocated on the heap (any class you create with a 'new' statement, directly or indirectly, is actually allocated onto the heap). If the reference count for that object is 0, it finalizes the object (in other words, it calls the Finalize method of the object. You implement this method by supplying a destructor in C#, as opposed to actually overriding the Finalize method like you might expect). After this method has been called, the object is "marked" (not literally) as finalized. On the next pass, all objects "marked" as finalized will be removed from memory entirely.
 
Unfortunately, there is no way to explicitly remove an object from memory. You can't call an object's Finalize method, and setting a reference to null doesn't necessarily remove all references from that object. For example, the following does not ensure that the variable named "obj" will no longer exist in memory.
 
Object obj = new Object();
CallSomeMethod(obj);
obj = null;
 
CallSomeMethod is just any method that takes an object as a parameter. Now, if you're not familiar with the process, you would probably assume that obj is now no longer residing in memory, and the GC is preparing to clean it up. However, this may not actually be the case. What if CallSomeMethod added obj to a collection, or passed it to another method, which stored the reference somewhere? The object would not be eligible for garbage collection because some code could still access it, and thus, it won't be cleaned from memory, even though 'obj' points to null.
 
Unmanaged resources are a whole different story in .NET. The GC doesn't "know" how to interact with these resources; it doesn't know how to clean them up. By unmanaged resources, I mean file streams, database connections, some COM objects (for instance, a Word interop application instance), and other things. You may be thinking "but howcome if I open a FileStream and don't explicitly destroy it, it doesn't just exist forever, locking the file?" This is because the .NET developers have implemented ways to clean up the unmanaged resources on their own accord. But what about the times that we don't tell the object to clean itself up? Won't the unmanaged resources just stay in memory forever, or until the computer shuts off? The answer would be yes if the .NET developers hadn't come up with a way to make this easier on us, too. They place code that releases the unmanaged resources in the object's destructor, so when the object can no longer be referenced, it can be finalized. When it is finalized, those method(s) are called, cleaning up the resources.
 
Well, what about IDisposable, and its famous Dispose method? Surely, calling Dispose on an object should destroy it and remove it form memory! Unfortunately, this isn't the case. There is nothing special about the Dispose method--no extra code is injected into the method when you implement, nothign special happens when it is called, unless you provide that functionality. The Dispose method is just a standard throughout .NET, a good convention, that makes it easier for us to remember to clean up after ourselves when we can.
 
There is a lot more to it, but those are the 'basics'. There are a few ways in which you can interact with the GC, and they are accessed through the static class System.GC. It is usually not recommended you use these methods, as the GC usually performs much better undisturbed. However, there are some cases that you may want to communicate with the GC. For example, in most .NET Dispose methods, the object usually unregisters itself for finalization. Because nothing useful will happen in the destructor anyway (unless you put some functionality there), you can tell the GC to omit the Finalize stage, and clean the object from memory as soon as its reference count hits 0 and the GC makes its pass. You do this by calling the System.GC.SuppressFinalize(objectToSupressFinalizeFor) method. If you've ever used Red-Gate's Reflector, you've probably seen a bunch of calls to "System.GC.SupressFinalize(this);" in Dispose methods. This simply tells the GC that the destructor doesn't need to be called for this object, because you've already done your cleaning up before-hand. If you call this method on an object and want to 'cancel' this behaviour, call System.GC.ReRegisterForFinalize(objectToReRegister).
 
Though it is extremely rare, GC.Collect() can also be a useful method. It 'forces' the GC to run a pass through the objects on the heap, and evaluate whether it should remove them, finalize them or ignore them. You may find uses for some of the other methods in System.GC, but it's rather doubtful, as they're meant for very rare cases only. As I said, the GC works best when left alone. It knows how to do its job much better than you or I do.


Hope that helped,
 
Nate

 

by: brettrPosted on 2009-11-05 at 20:39:31ID: 25756642

I understand how GC work but don't understand the results I'm seeing with the included code, which comes from a winform app.  When button1 is clicked, I create a new class with 100 objects in it.  When button2 is clicked, I null out the class.  I never see a descrease in memory, only increases.

I also see memory increase when simply mousing over the buttons.  I'm using .NET 3.5 on Vista Home Premium 64bit.  Any ideas on the memory behavior?

    public partial class Form1 : Form
    {
        MyClass c;
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            c = new MyClass();
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            c = null;
        }
    }
 
    public class MyClass
    {
        List<object> l = new List<object>();
        public MyClass()
        {
            for (int i = 0; i < 100; i++)
            {
                l.Add(new object());
            }
        }
    }
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

Select allOpen in new window

 

by: InternalStaticPosted on 2009-11-06 at 08:22:37ID: 25760489

You're thinking of memory too primitively. Memory management is, by no means, simple in any way.

For example, most modern video cards (whether integrated or not) have a small processing unit, simliar to a CPU, built into the chip itself. The chip, called a GPU (Graphics Processing Unit), is geared towards graphical processing, so most graphical calls are (in theory) sent to this GPU.

Also, because you're using Windows Forms, there is a crap load of stuff you don't see going on under the hood Just because you don't subscribe to a MouseHover or MouseMove event doesn't mean the event won't be triggered when it happens. Your windows forms are accepting all messages from the mouse/keyboard at all times, whether you want them or not. Monitoring memory in the way you're attempting to is not practical, and seeing a noticeable difference is extremely unlikely (especially because an instance of an Object has no data, anyway; the reference will just but 8 bytes, in your case, being on a 64 bit system. In other words, each instance of MyClass would only take up under a kilobyte. Of course, this is only theory. This stuff may be just optimized out by the compiler completely).

If you'd like to see what goes on in your application, check out the Red-Gate Reflector. It can analyze MSIL and reconstruct it into what it may have looked like in C#, Managed C++, Delphi, MSIL Assembly, or (hate to sya this last one...) VB.NET. Very valuable tool in the scope of learning.

 

by: brettrPosted on 2009-11-06 at 08:52:27ID: 25760789

Why would I reconstruct it?  I have the source code.

 

by: InternalStaticPosted on 2009-11-06 at 16:14:22ID: 25764250

>>Why would I reconstruct it?  I have the source code.

I'm not talking about your own code. I'm talking about what actually goes on in your application when you call certain methods and do certain things. You may be surprised to hear that adding a Control to a form via controlName.Controls.Add(someControl) actually results in dozens of method calls and assignment statements. The stuff you put into the application is only a tiny, tiny portion of what really goes on under the hood. When I suggest that you reconstruct it, I'm suggesting you reconstruct one of the .NET libraries, such as System.Windows.Forms.dll, of which you do not have the source code for. Take a look at a simple Button. The results may (or may not) surprise you.

Remember, however, that only MSIL can be re-constructed, so you can't analyze the Windows Kernel DLL or anything like that.

As an example, I've posted the reconstruction to a simple call MessageBox's "Show", along with one of the method's it relies on ("ShowCore", which is hidden due to its private access modifier).

// One might think a call to this method is pretty standard. However, just look at the method it calls in turn (below this method, 'ShowCore')
public static DialogResult Show(string text)
{
    return ShowCore(null, text, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0, false);
}
 
private static DialogResult ShowCore(IWin32Window owner, string text, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, bool showHelp)
{
    DialogResult result;
    if (!ClientUtils.IsEnumValid(buttons, (int) buttons, 0, 5))
    {
        throw new InvalidEnumArgumentException("buttons", (int) buttons, typeof(MessageBoxButtons));
    }
    if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(icon, 4, 0, 4))
    {
        throw new InvalidEnumArgumentException("icon", (int) icon, typeof(MessageBoxIcon));
    }
    if (!WindowsFormsUtils.EnumValidator.IsEnumWithinShiftedRange(defaultButton, 8, 0, 2))
    {
        throw new InvalidEnumArgumentException("defaultButton", (int) defaultButton, typeof(DialogResult));
    }
    if (!SystemInformation.UserInteractive && ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0))
    {
        throw new InvalidOperationException(SR.GetString("CantShowModalOnNonInteractive"));
    }
    if ((owner != null) && ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0))
    {
        throw new ArgumentException(SR.GetString("CantShowMBServiceWithOwner"), "options");
    }
    if (showHelp && ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) != 0))
    {
        throw new ArgumentException(SR.GetString("CantShowMBServiceWithHelp"), "options");
    }
    if ((options & ~(MessageBoxOptions.RtlReading | MessageBoxOptions.RightAlign)) != 0)
    {
        IntSecurity.UnmanagedCode.Demand();
    }
    IntSecurity.SafeSubWindows.Demand();
    int type = showHelp ? 0x4000 : 0;
    type |= ((buttons | ((MessageBoxButtons) ((int) icon))) | ((MessageBoxButtons) ((int) defaultButton))) | ((MessageBoxButtons) ((int) options));
    IntPtr zero = IntPtr.Zero;
    if (showHelp || ((options & (MessageBoxOptions.ServiceNotification | MessageBoxOptions.DefaultDesktopOnly)) == 0))
    {
        if (owner == null)
        {
            zero = UnsafeNativeMethods.GetActiveWindow();
        }
        else
        {
            zero = Control.GetSafeHandle(owner);
        }
    }
    IntPtr userCookie = IntPtr.Zero;
    if (Application.UseVisualStyles)
    {
        userCookie = UnsafeNativeMethods.ThemingScope.Activate();
    }
    Application.BeginModalMessageLoop();
    try
    {
        result = Win32ToDialogResult(SafeNativeMethods.MessageBox(new HandleRef(owner, zero), text, caption, type));
    }
    finally
    {
        Application.EndModalMessageLoop();
        UnsafeNativeMethods.ThemingScope.Deactivate(userCookie);
    }
    UnsafeNativeMethods.SendMessage(new HandleRef(owner, zero), 7, 0, 0);
    return result;
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:

Select allOpen in new window

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...