1

I was wondering if this code leak :

int main()
{
boost::ptr_vector <char> v;
v.push_back(new char[10]);
v.clear()
}

Will the ptr_vector destructor or clear() function delete the pointers it contains or do i have to do it myself?

Ephemere
  • 121
  • 1
  • 6
  • `v.push_back(new char[10]);` I don't think this does what you think it does. Looking at the Boost documentation `push_back` only covers a single elements. (At any rate there'd be no way for the callee to know the size of your allocation.) – asveikau Feb 09 '11 at 20:23
  • It's adding a dynamic char array to the ptr_vector. It's use in the code i'm reviewing and it works fine, but i'm not sure the memory is released. – Ephemere Feb 09 '11 at 20:27
  • 5
    @Ephemere: Following `new[]` with `delete` invokes undefined behavior. It's pure coincidence that it appears to work fine. – fredoverflow Feb 09 '11 at 20:30
  • 2
    Also, it appears you simply want a `std::vector`. – fredoverflow Feb 09 '11 at 20:44
  • FredOverflow is right, try running your code through valgrind or something similar. – Jan Feb 09 '11 at 20:58
  • @FredOverflow: The char array is actually use as a byte array in the code, this is why string isn't use, otherwise it sure be my choice. – Ephemere Feb 09 '11 at 21:03
  • In that case, what's wrong with `std::vector >`? – fredoverflow Feb 09 '11 at 21:07

1 Answers1

-3

From the vector documentation (http://www.cplusplus.com/reference/stl/vector/~vector/):

Vector destructor

Destructs the container object. This calls each of the contained element's destructors, and deallocates all the storage capacity allocated by the vector.

delete[] won't be called, so it'll leak. And as other commenters pointed out, there are more STL ways to do it.

SteveMc
  • 1,386
  • 8
  • 11