+ Reply to Thread
Results 1 to 2 of 2

Thread: Following code introduces memory leakage? How o resolve this?

  1. #1

    Following code introduces memory leakage? How o resolve this?

    Following code is leaking memory:

    Code:
    class MyData1
    {
    private:
    	int _data ;
    public:
    	MyData1(int data)
    	{
    		_data = data ;
    	}
    } ;
    
    void MyVector()
    {
    	std::vector<MyData1 *> myDataArray ;
    
    	myDataArray.push_back(new MyData1(10)) ;
    	myDataArray.push_back(new MyData1(20)) ;
    	myDataArray.push_back(new MyData1(30)) ;
    
    
    	myDataArray.clear() ;
    }
    Even though I clear items from the vector, it is leaking memory.

    I can see in debug output window under VC++ IDE.

    What is wrong with it?

  2. #2
    std::vector:clear will delete items from the vector itself.

    It will not delete items that is allocated dynamically as you did.

    So, you will need to iterate through vector and delete each item individually as described below:

    Code:
    void MyVector()
    {
    	std::vector<MyData1 *> myDataArray ;
    
    	myDataArray.push_back(new MyData1(10)) ;
    	myDataArray.push_back(new MyData1(20)) ;
    	myDataArray.push_back(new MyData1(30)) ;
    
    
    	std::vector<MyData1 *>::iterator itr = myDataArray.begin() ;
    	for(; itr != myDataArray.end(); itr++)
    	{
    		MyData1 *p = *itr ;
    		delete p ;
    		p = NULL ;
    	}
    
    	myDataArray.clear() ;
    }
    Then you can call vector::clear.

    Hope this helps.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

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