1

I got a set that includes pointers to an allocated memory, I am using the clear method forexample : setname.clear(); and the set itself is getting cleared and his pointers but I still get memory leaks because the allocated memory stays uncleared for some reason.

bpeterson76
  • 12,918
  • 5
  • 49
  • 82
Nadav
  • 2,589
  • 9
  • 44
  • 63

3 Answers3

8

std::set's clear() method does remove elements from the set. However, in your case set contains pointers that are being removed, but the memory they point to is not released. You have to do it manually before the call to clear(), for example:

struct Deleter
{
  template <typename T>
  void operator () (T *ptr)
  {
     delete ptr;
  }
};

for_each (myset.begin (), myset.end (), Deleter());

There is a library in Boost called Pointer Container that solves this problem.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • Or, if Boost is available, try making it a set of boost::shared_ptr (from Boost.SmartPtr: http://www.boost.org/doc/libs/1_44_0/libs/smart_ptr/smart_ptr.htm). TR1 has smart_ptr as well, I believe. – gregg Sep 23 '10 at 14:15
  • shared_ptr would be a great overhead if pointer is not really shared, but just resides in the set (to avoid copying, for example). This was exactly one of the motivations to to create ptr_container. –  Sep 23 '10 at 14:23
  • @Vlad Lazarenko what if the set contains int? – Pegah Nov 22 '11 at 22:30
  • @Pegah: `int` or `int *`? You don't have to allocate memory on the heap for `int`... –  Nov 22 '11 at 22:35
  • @Vlad Lazarenko I have a set of integer values, I have defined it as a type: typedef __gnu_cxx ::hash_set intset; and then I have a set like this: inset s; now if I write s.clea(); the memory would not be freed, would it? – Pegah Nov 22 '11 at 22:37
4

Set only clears what it allocates itself. If you allocate something yourself, you'll have to clear it yourself.

yorick
  • 1,474
  • 10
  • 8
3

Clear() only removes the pointers not the object it points to. You'll have either to iterate on each object before removing it to delete it, or use something like std::tr1::shared_ptr (also in Boost).

Wernight
  • 36,122
  • 25
  • 118
  • 131