Is valgrind crazy or is this is a genuine std map iterator memory leak?

Posted by Alberto Toglia on Stack Overflow See other posts from Stack Overflow or by Alberto Toglia
Published on 2010-05-20T10:15:47Z Indexed on 2010/05/20 10:20 UTC
Read the original article Hit count: 209

Filed under:
|
|
|
|

Well, I'm very new to Valgrind and memory leak profilers in general. And I must say it is a bit scary when you start using them cause you can't stop wondering how many leaks you might have left unsolved before!

To the point, as I'm not an experienced in c++ programmer, I would like to check if this is certainly a memory leak or is it that Valgrind is doing a false positive?

typedef std::vector<int> Vector;
typedef std::vector<Vector> VectorVector; 
typedef std::map<std::string, Vector*> MapVector; 
typedef std::pair<std::string, Vector*> PairVector; 
typedef std::map<std::string, Vector*>::iterator IteratorVector;

VectorVector vv; MapVector m1;
MapVector m2;

vv.push_back(Vector());
m1.insert(PairVector("one", &vv.back()));

vv.push_back(Vector());
m2.insert(PairVector("two", &vv.back()));

IteratorVector i = m1.find("one"); 
i->second->push_back(10);
m2.insert(PairVector("one", i->second));

m2.clear(); m1.clear(); vv.clear();

Why is that? Shouldn't the clear command call the destructor of every object and every vector?

Now after doing some tests I found different solutions to the leak:

1) Deleting the line i->second->push_back(10);

2) adding a delete i->second; after it's been used.

3) Deleting the second vv.push_back(Vector()); and m2.insert(PairVector("two", &vv.back())); statements.

Using solution 2) makes Valgring print: 10 allocs, 11 frees Is that OK?

As I'm not using new why should I delete?

Thanks, for any help!

© Stack Overflow or respective owner

Related posts about c++

Related posts about valgrind