CodeGuru Forums -
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic Newsletters VB Forums Developer.com


Newest CodeGuru.com Articles:

  • Binding Data to Silverlight 4.0 Controls Using ASP.NET MVC Framework 2.0
  • ADO.NET Data Services in the .NET Framework
  • Visual C++ Programming: What's new for MFC library in VC++ 2010?
  • Microsoft Visual Studio LightSwitch and What It Can Do For You

  • Search CodeGuru:
     



    Go Back   CodeGuru Forums > .NET Programming > C-Sharp Programming
    FAQ Members List Calendar Search Today's Posts Mark Forums Read

    C-Sharp Programming Post questions, answers, and comments about C#.

    Reply
     
    Thread Tools Search this Thread Rate Thread Display Modes
      #1    
    Old November 5th, 2008, 02:20 AM
    code? code? is offline
    Member
     
    Join Date: May 2006
    Posts: 306
    code? is on a distinguished road (20+)
    Memory leak example?

    Is there any way I can do a tiny memory leak application, to see what it would do? Just wondering for experimental reasons.
    Reply With Quote
      #2    
    Old November 5th, 2008, 02:31 AM
    wildfrog's Avatar
    wildfrog wildfrog is offline
    Elite Member
     
    Join Date: Apr 2005
    Location: Norway
    Posts: 3,934
    wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)wildfrog has a reputation beyond repute (3000+)
    Re: Memory leak example?

    You could keep on adding elements to some kind of collection (List, Dictionary etc.).

    - petter
    __________________
    I love deadlines. I like the whooshing sound they make as they pass by - Douglas Adams.
    Visit me!.

    Use code-tags! [code]Your code here[/code]
    Reply With Quote
      #3    
    Old November 5th, 2008, 06:53 AM
    TheCPUWizard's Avatar
    TheCPUWizard TheCPUWizard is offline
    Elite / Microsoft MVP
    Power Poster
     
    Join Date: Mar 2002
    Location: NY, USA
    Posts: 12,095
    TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)
    Re: Memory leak example?

    Quote:
    Originally Posted by wildfrog
    You could keep on adding elements to some kind of collection (List, Dictionary etc.).

    - petter
    How would that generate a leak????
    __________________
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009
    In theory, there is no difference between theory and paractice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

    Reply With Quote
      #4    
    Old November 5th, 2008, 10:23 AM
    DeepT DeepT is offline
    Senior Member
     
    Join Date: Sep 2004
    Posts: 1,302
    DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)
    Re: Memory leak example?

    The classic memory leak in C# come from event handlers.

    Take some core object that never goes away for the life of the application. Then take some other object which instanced for a while and then it is supposed to go away.

    The Other object subscribes to an event on the core object. Now the core object has a reference to this other object in its event handler. You go along and empty your collection of objects thinking the GC will clean everything up. However, those objects never get cleaned up, because Core object's event has a reference to it.

    The fix for this is simply to unsubscribe to the event, thus removing the reference.
    Reply With Quote
      #5    
    Old November 5th, 2008, 12:20 PM
    TheCPUWizard's Avatar
    TheCPUWizard TheCPUWizard is offline
    Elite / Microsoft MVP
    Power Poster
     
    Join Date: Mar 2002
    Location: NY, USA
    Posts: 12,095
    TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)
    Re: Memory leak example?

    Quote:
    Originally Posted by DeepT
    The classic memory leak in C# come from event handlers.

    Take some core object that never goes away for the life of the application. Then take some other object which instanced for a while and then it is supposed to go away.

    The Other object subscribes to an event on the core object. Now the core object has a reference to this other object in its event handler. You go along and empty your collection of objects thinking the GC will clean everything up. However, those objects never get cleaned up, because Core object's event has a reference to it.

    The fix for this is simply to unsubscribe to the event, thus removing the reference.
    This is a VERY common problem. I find it in about 80% of .NET applications I am called in on.

    Technically this is not a leak, as:

    1) The object is still referencable (ie the event will continue to call it)
    2) The object will be properly destroyed (albiet at program termination).

    One common solution it to use the "Weak Event Model". However this does add some overhead on each invokation of the event.

    A less common but [IMHO] better solution is the "Owned Delegate Model". In this model there is a bidirectional tie between the (wrapper for the) delegate and the recieving object.

    MANUALLY unsubscribing works, but it is soo easy to miss
    __________________
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009
    In theory, there is no difference between theory and paractice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

    Reply With Quote
      #6    
    Old November 5th, 2008, 01:12 PM
    DeepT DeepT is offline
    Senior Member
     
    Join Date: Sep 2004
    Posts: 1,302
    DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)
    Re: Memory leak example?

    In a manged language it is a close to a memory leak as you can get. If you (not CPUWizard, but people in general) wanted to be super-anal about it, you would simply say memory leaks are impossible and strike the word from the C# lexicon.

    Now you could go on about unmanaged code, but we are talking about managed code, C#, not COM interoperability or DLLs written in C++ that can leak.
    Reply With Quote
      #7    
    Old November 5th, 2008, 01:14 PM
    DeepT DeepT is offline
    Senior Member
     
    Join Date: Sep 2004
    Posts: 1,302
    DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)
    Re: Memory leak example?

    Quote:
    Originally Posted by TheCPUWizard
    A less common but [IMHO] better solution is the "Owned Delegate Model". In this model there is a bidirectional tie between the (wrapper for the) delegate and the recieving object.
    An example of this would be great.
    Reply With Quote
      #8    
    Old November 5th, 2008, 01:52 PM
    TheCPUWizard's Avatar
    TheCPUWizard TheCPUWizard is offline
    Elite / Microsoft MVP
    Power Poster
     
    Join Date: Mar 2002
    Location: NY, USA
    Posts: 12,095
    TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)
    Re: Memory leak example?

    Quote:
    Originally Posted by DeepT
    An example of this would be great.
    A "working" example would be too big to post here (might be time for an article ), but The concept is simple....

    (This code is typed in RAW and for conceptual purposes only...)
    Code:
        public class OwnedDelegates : List<OwnedDelegate>
        {
            public static OwnedDelegates Global = new OwnedDelegates();
            public void Register(OwnedDelegate item)
            {
                Add(item);
            }
    
            public void Unregister(OwnedDelegate item)
            {
                Remove(item);
            }
    
    
            public void ReleaseAll(object owner)
            {
                List<OwnedDelegate> killList = new List<OwnedDelegate>();
                foreach (OwnedDelegate item in this)
                {
                    if (item.IsOwnedBy(owner))
                    {
                        item.Invalidate();
                        killList.Add(item);
                    }
                }
                foreach (OwnedDelegate item in killList)
                {
                    Remove(item);
                }
            }
        }
    
        public abstract class OwnedDelegate
        {
            public abstract void Invalidate();
            public abstract bool IsOwnedBy(Object owner);
            public abstract bool IsAlive { get; }
        }
    
        public class OwnedDelegate<EVENT_TYPE> : OwnedDelegate
            where EVENT_TYPE : EventArgs
        {
            public static EventHandler<EVENT_TYPE> Create(EventHandler<EVENT_TYPE> handler)
            {
                OwnedDelegate<EVENT_TYPE> instance = new OwnedDelegate<EVENT_TYPE>(handler);
                OwnedDelegates.Global.Register(instance);
                return instance.Delegate;
            }
    
            public override bool IsOwnedBy(Object owner)
            {
    
                if (IsAlive)
                    return ReferenceEquals(m_Owner.Target, owner);
                else
                    return false;
            }
    
             public override bool IsAlive
            {
                get { return (m_Owner != null) && (m_Owner.IsAlive); }
             }
    
            public override void Invalidate()
            {
                m_RealHandler = null;
                m_Owner = null;
                OwnedDelegates.Global.Unregister(this);
            }
    
            private OwnedDelegate(EventHandler<EVENT_TYPE> handler)
            {
                m_Owner = new WeakReference(handler.Target);
                m_RealHandler = handler;
                m_MyHandler += OwnedDelegate_Handler;
            }
    
            public EventHandler<EVENT_TYPE> Delegate
            {
                get { return m_MyHandler; }
            }
    
            void OwnedDelegate_Handler(object sender, EVENT_TYPE e)
            {
                if (m_RealHandler != null)
                    m_RealHandler(sender, e);
            }
    
            private WeakReference m_Owner;
            private event EventHandler<EVENT_TYPE> m_MyHandler;
            private EventHandler<EVENT_TYPE> m_RealHandler;
        }
    __________________
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009
    In theory, there is no difference between theory and paractice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

    Reply With Quote
      #9    
    Old November 5th, 2008, 01:58 PM
    Mutant_Fruit Mutant_Fruit is offline
    Senior Member
     
    Join Date: May 2007
    Posts: 1,344
    Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)
    Re: Memory leak example?

    Just keep calling:

    System.Runtime.InteropServices.Marshal.AllocHGlobal(10000);

    and don't free the returned pointer.
    __________________
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
    Reply With Quote
      #10    
    Old November 5th, 2008, 02:02 PM
    DeepT DeepT is offline
    Senior Member
     
    Join Date: Sep 2004
    Posts: 1,302
    DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)
    Re: Memory leak example?

    That will take a couple of read-throughs, or maybe find a book. Or you can create an article on it.
    Reply With Quote
      #11    
    Old November 5th, 2008, 02:04 PM
    DeepT DeepT is offline
    Senior Member
     
    Join Date: Sep 2004
    Posts: 1,302
    DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)
    Re: Memory leak example?

    Quote:
    Originally Posted by Mutant_Fruit
    Just keep calling:

    System.Runtime.InteropServices.Marshal.AllocHGlobal(10000);

    and don't free the returned pointer.
    That is cheating and doesn't count. Once you leave the managed side of things, you are "out of bounds".

    I can come up with better one then that

    public void Loop() { Loop();}

    Last edited by DeepT; November 5th, 2008 at 02:06 PM.
    Reply With Quote
      #12    
    Old November 5th, 2008, 02:09 PM
    TheCPUWizard's Avatar
    TheCPUWizard TheCPUWizard is offline
    Elite / Microsoft MVP
    Power Poster
     
    Join Date: Mar 2002
    Location: NY, USA
    Posts: 12,095
    TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)
    Re: Memory leak example?

    DeepT ---- Just found out you do not have PM's enabled....please contact me.

    DO NOT REPLY directly on forum to this particular reply. It will be deleted once contact is made.
    __________________
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009
    In theory, there is no difference between theory and paractice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

    Reply With Quote
      #13    
    Old November 5th, 2008, 02:12 PM
    Mutant_Fruit Mutant_Fruit is offline
    Senior Member
     
    Join Date: May 2007
    Posts: 1,344
    Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)Mutant_Fruit is a splendid one to behold (750+)
    Re: Memory leak example?

    A stack overflow isn't a memory leak :P

    You can't create a memory leak in C# unless you are exploiting a bug in the framework or are using unmanaged code.

    Pure safe C# cannot leak.
    __________________
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
    Reply With Quote
      #14    
    Old November 6th, 2008, 08:44 AM
    DeepT DeepT is offline
    Senior Member
     
    Join Date: Sep 2004
    Posts: 1,302
    DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)DeepT  is a jewel in the rough (300+)
    Re: Memory leak example?

    I will define a memory leak for C#:

    A leak is when your program consumes more and more memory and you have no idea why.
    Reply With Quote
      #15    
    Old November 6th, 2008, 09:19 AM
    TheCPUWizard's Avatar
    TheCPUWizard TheCPUWizard is offline
    Elite / Microsoft MVP
    Power Poster
     
    Join Date: Mar 2002
    Location: NY, USA
    Posts: 12,095
    TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)TheCPUWizard has a reputation beyond repute (3000+)
    Re: Memory leak example?

    Quote:
    Originally Posted by DeepT View Post
    I will define a memory leak for C#:

    A leak is when your program consumes more and more memory and you have no idea why.
    One can not simply make up definitions for a word...unless...
    I hereby define "fun" as "Send large sums of money to the CPUWizard". I want EVERYBODY th have FUN!!!!!
    A leak is characterized by two qualities.

    1) The resource is not referencable
    2) The resource will not be properly "cleaned up".

    Unless these two conditions come into play, it is NOT a leak!!!!!!

    Improper Object Lifetime Management is a completely different topic. "Excessive" memory usage is one symptom of this.

    Two ironic points:

    1) EXPLICITLY calling GC.Collect can actually induce increased memory usage.

    2) .NET really does not have "garbage collection" for most objects (objects with 85,000 or more bytes of direct allocation are the exception). On the other hand native C++ almost ALWAYS has "garbage collection".
    __________________
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009
    In theory, there is no difference between theory and paractice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

    Reply With Quote
    Reply

    Bookmarks
    Go Back   CodeGuru Forums > .NET Programming > C-Sharp Programming


    Thread Tools Search this Thread
    Search this Thread:

    Advanced Search
    Display Modes Rate This Thread
    Rate This Thread:

    Posting Rules
    You may not post new threads
    You may not post replies
    You may not post attachments
    You may not edit your posts

    BB code is On
    Smilies are On
    [IMG] code is On
    HTML code is Off
    Forum Jump


    All times are GMT -5. The time now is 04:29 PM.



    Acceptable Use Policy

    Internet.com
    The Network for Technology Professionals

    Search:

    About Internet.com

    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers


    Powered by vBulletin® Version 3.7.3
    Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.