Is valgrind crazy or is it a true std map iterator memory leak?

Ok, I'm very new to Valgrind and memory leak profiles in general. And I have to say that it’s a little scary when you start using them, because you can’t stop wondering how many leaks you could have left unsolved before!

Due to the fact that I am not an experienced C ++ programmer, I would like to check if this is a memory leak or that Valgrind is doing a false result?

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? Should a clear command invoke the destructor of each object and each vector?

Now, after several tests, I have found various leak solutions:

1) Removal:

i->second->push_back(10);

2) Addition:

delete i->second;

3) Removing the second

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

Using solution 2) does Valgring print: 10 allocs, 11 frees Is this normal?

, ?

, !

+5
3

:

i->second->push_back(10);

, i- > second , :

vv.push_back(Vector());

.

. vv , . , , . , .

, vv-. , , -, .

std::list<Vector> vv;  // insertion into this will not invalidate any other members.
                       // Thus any pointers to members you have will not become invalidated.

, .
, , .
, .

std::map<std::string, std::vector<int> >    m1;

m1["one"].push_back(10);
m1["two"].push_back(20);
+2

undefined :

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

vv.push_back(Vector());

, , , , , .

Valgring: 10 allocs, 11 frees ?

, - -frees?

, vector (, list deque, , ). ( , ) , .

+1

. , .

std::vector<>::push_back() std::vector<>, . std::vector<> , ( ), , , .

This means that all calls push_back()in your code (except the first one) lead to undefined behavior, so there might be something here.

0
source

All Articles