Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clearing a vector of pointers [duplicate]

Assume I have defined a class like this:

 class foo {  private:      std::vector< int* > v;  public:     ...     void bar1()     {        for (int i = 0; i < 10; i++) {          int *a = new int;          v.push_back( a );        }     };      void bar2()     {        std::vector< int >::iterator it = v.begin();        for ( ; it != v.end(); it++ )            std::cout << (*it);        v.clear();     }  }; 

In short, I push back some pointers in a vector, later I clear the vector. The question is, does this code has memory leak? I mean by clearing the vector, are the pointers deleted properly?

like image 944
mahmood Avatar asked Oct 09 '12 07:10

mahmood


People also ask

Do you need to delete a vector of pointers?

Yes, the code has a memory leak unless you delete the pointers. If the foo class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.

How do you clear a vector of a pointer in C++?

In short deleting a vector of pointers without creating any memory leaks. delete *it; tckts. erase(tckts.

How do you deallocate a vector pointer?

The vector contains pointers. erase() will remove a pointer from the vector, but will not free the object that the pointer is pointing at. You have to free the object separately.

How do I completely clear a vector content?

All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.


1 Answers

Yes, the code has a memory leak unless you delete the pointers. If the foo class owns the pointers, it is its responsibility to delete them. You should do this before clearing the vector, otherwise you lose the handle to the memory you need to de-allocate.

   for (auto p : v)    {      delete p;    }     v.clear(); 

You could avoid the memory management issue altogether by using a std::vector of a suitable smart pointer.

like image 97
juanchopanza Avatar answered Sep 27 '22 21:09

juanchopanza