CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: Is there any memory leak in the code snippet?

  1. #1

    Is there any memory leak in the code snippet?

    Code:
    #include <iostream>
    using namespace std;
    
    class A
    {
      int x;
       
    public:
       A(int x1) {x=x1;}
       virtual void fun() {cout<<"A";} 
       ~ A(){  }; 
    };
    
    class B: public A
    {
      int y;
       
    public:
       B(int x1,int y1):A(x1) {y=y1;}
       virtual void fun( ) {cout<<"B \n";} 
       ~ B(){  }; 
    };
    
    int main()
    {
    
       A* a1=new B(1,2);  // Is there any memory leak as destructor is not declared as virtual ? 
       a1->fun();                // Object of B is created on heap 
    
       B b2(3,4);                // Is there any memory leak as destructor is not declared as virtual ?
       A* a2= &b2;            // Object of B is created on stack
       a2->fun(); 
    
      delete a1;   //Deleting obejct created on heap but it wont call destructor of class B as it's not vritual.
    }
    Last edited by forumuser11@gmail.com; October 5th, 2010 at 11:53 PM.

  2. #2
    Join Date
    May 2009
    Posts
    2,413

    Re: Is there any memory leak in the code snippet?

    ---
    Last edited by nuzzle; October 6th, 2010 at 06:42 AM.

  3. #3
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Is there any memory leak in the code snippet?

    You have a potential memory leak, and a potential for a future memory leak:

    Code:
       A* a1=new B(1,2);  // Is there any memory leak as destructor is not declared as virtual ? 
       a1->fun();                // Object of B is created on heap
    If fun throws an exception, then you've just leaked. Right now, the chances that fun does throw are slim to none, but not inexistant. Furthermore, somebody could change func in the future in such a way that an exception be thrown, and you'd be none the wiser.

    Code:
       A* a1=new B(1,2);  // Is there any memory leak as destructor is not declared as virtual ? 
       a1->fun();                // Object of B is created on heap 
    
       bool monarch_bug_fix = is_valid(a1);
       if (monarch_bug_fix == false)
       {
          return; //a1 is not valid in this context, we exit
                  //Oops, forgot to clean up.
       }
    
       B b2(3,4);                // Is there any memory leak as destructor is not declared as virtual ?
       A* a2= &b2;            // Object of B is created on stack
       a2->fun();
    
    
      delete a1;   //Deleting obejct created on heap but it wont call destructor of class B as it's not vritual.
    I magine somebody in the future makes a change to your code and inserts a premature return. leak.

    Anytime you don't use managed resource, you have a huge potential for leaks.

    To answer your question though, the rule is pretty easy. An object that is newed must be destroyed by the corresponding delete. For a stack based object, that is always the case. For newed object, you can either make the destructor virtual (so you are guaranteed to call the right destructor polymorphically), or you can pray you call the correct destructor (ie, call delete on the right type)
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  4. #4
    Join Date
    Oct 2008
    Posts
    1,456

    Re: Is there any memory leak in the code snippet?

    actually, deleting a pointer to a base class which points to a derived object whose base has a non virtual destructor gives undefined behavior. Therefore, the line "delete a1;" gives undefined behavior ( which includes the possibility of a memory leak; indeed, if I remember well, that line will leak memory or corrupt the heap in VC++ 2008 ).

  5. #5

    Re: Is there any memory leak in the code snippet?

    I agree with this point. Even if the derived class do not contain dynamic memory allocation, destructor in base class MUST be declared virtual to avoid any undefined behaviour.
    Do you agree?

    Code:
    #include <iostream>
    using namespace std;
    
    class A
    {
      int x;
       
    public:
       A(int x1) {x=x1;}
       virtual void fun() {cout<<"A";} 
       virtual ~ A(){  }; //Destructor must be declared virtual...
    };
    
    class B: public A
    {
      int y;
       
    public:
       B(int x1,int y1):A(x1) {y=y1;}
       virtual void fun( ) {cout<<"B \n";} 
       ~ B(){  }; 
    };
    
    int main()
    {
       B b2(3,4);                // Is there any memory leak as destructor is not declared as virtual ?
       A* a2= &b2;            // Object of B is created on stack
       a2->fun(); 
    }

  6. #6
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Is there any memory leak in the code snippet?

    If you intended to delete through a base class pointer, yes.

    (Note that it is never valid to delete[] an array of derived objects through a base class pointer.)

  7. #7
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,768

    Re: Is there any memory leak in the code snippet?

    Quote Originally Posted by forumuser11@gmail.com
    I agree with this point. Even if the derived class do not contain dynamic memory allocation, destructor in base class MUST be declared virtual to avoid any undefined behaviour.
    Do you agree?
    I disagree. It is a should, not a must, since undefined behaviour might not actually occur even if the base class destructor is not virtual.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  8. #8
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Is there any memory leak in the code snippet?

    The point is this:

    Code:
    Base p = new Derived;
    delete p;
    The line delete p will call Base::~Base. If it is virtual, than it will actual resolve to Derived::~Derived, and everything will be safe. If it isn't, then you'll call the base destructor on the derived object -> Boom.

    That said:

    Code:
    Derived p = new Derived;
    delete p;
    Here this code is perfectly fine regardless of virtuality of the destructor.

    As already mentioned: If your object will be destroyed via a base pointer, than yes, the destructor must be virtual.

    The perfect example of this is private inheritance. If you inherit privately from a base class, you know no one will handle your class via it's base, so you have no need for a virtual destructor.
    Last edited by monarch_dodra; October 6th, 2010 at 08:19 AM.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  9. #9
    Join Date
    May 2009
    Posts
    2,413

    Re: Is there any memory leak in the code snippet?

    Quote Originally Posted by forumuser11@gmail.com View Post
    I agree with this point. Even if the derived class do not contain dynamic memory allocation, destructor in base class MUST be declared virtual to avoid any undefined behaviour.
    Do you agree?
    I agree.

    I wasn't aware that the C++ standard defines the behaviour as undefined in this case. But since it does the destructor must be declare virtual as you say. Otherwise all bets are off.

  10. #10

    Re: Is there any memory leak in the code snippet?

    Laserlight,

    It's like in rainy season one should carry umbrella though there is no gurantee of rain...Similarly, as language std says deleing object of derived class through base class pointer is UNDEFINED behaviour...We should respect that and carry umbrella in rainy seasons though it may not rain....We never know when undefined behaviour happens...

    Other members,
    any comments?

  11. #11
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,768

    Re: Is there any memory leak in the code snippet?

    Quote Originally Posted by forumuser11@gmail.com
    It's like in rainy season one should carry umbrella though there is no gurantee of rain...Similarly, as language std says deleing object of derived class through base class pointer is UNDEFINED behaviour...We should respect that and carry umbrella in rainy seasons though it may not rain....We never know when undefined behaviour happens...
    Exactly.

    (As noted earlier, we're talking about public inheritance here though. For private inheritance it is not a concern.)
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  12. #12
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Is there any memory leak in the code snippet?

    Well I'll make one last comment. In your original code, there is no memory leak, there is undefined behaviour. Different things...
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  13. #13
    Join Date
    May 2009
    Posts
    2,413

    Re: Is there any memory leak in the code snippet?

    Quote Originally Posted by laserlight View Post
    I disagree. It is a should, not a must, since undefined behaviour might not actually occur even if the base class destructor is not virtual.
    That's a misconception.

    Just because you didn't notice anything in particular when the undefined behaviour moment passed, it sure did "occur".

  14. #14
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,768

    Re: Is there any memory leak in the code snippet?

    Quote Originally Posted by nuzzle
    That's a misconception.

    Just because you didn't notice anything in particular when the undefined behaviour moment passed, it sure did "occur".
    No. Refer to monarch_dodra's post #8, though you need to tweak the code snippets to make p a pointer in both cases.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  15. #15

    Re: Is there any memory leak in the code snippet?

    thanks everyone

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)