1

I am getting this error in valgrind report.

==31766== 8 bytes in 1 blocks are definitely lost in loss record 3 of 825

My code looks like:

struct FooList {
  FooList() {}
  FooList(const vector<Foo*>& fooList_): fooList(fooList_) {}
  ~FooList() {
      BOOST_FOREACH(Foo* fooPtr, fooList) {
        delete fooPtr;
      }
  }  
  vector<Foo*> fooList;
}

Foo* createFoo(bool flag)
{
  if(flag) return new FooDerivedA();
  else     return new FooDerivedB();
}

void main() 
{
  FooList fl;

  Foo* fooA = createFoo(true);
  // some manipulation on fooA, if an exception happens at this point, the memory leaks.
  fl.fooList.push_back(fooA);

  Foo* fooB = createFoo(false);
  // some manipulation on fooB, if an exception happens at this point, the memory leaks.
  fl.fooList.push_back(fooB);

  // fl's desctructor will release memory for all elements.
}

I am not sure if it's because the new and delete statement are not in the same function which causes the definitely lost. How can I fix this?

Stan
  • 37,207
  • 50
  • 124
  • 185

0 Answers0