PDA

View Full Version : [C++] clearing a map?



Danii
January 1st, 2007, 10:05 PM
on to my next c++ issue..
I cant seem to get rid of a memory leak when using a map.
I tried this code i found on the net which is supposed to solve the problem but even this isnt working.


int main()
{
std::map<int, char*> Mappy;

for(int Index = 0; Index < 1024*1024; ++Index)
Mappy.insert(std::make_pair(Index, new char[10]));

for(std::map<int, char*>::iterator MapItor = Mappy.begin(); MapItor != Mappy.end(); ++MapItor)
{
char* Value = (*MapItor).second;
delete Value;
}
cout << "tömd: ";
cin.get();
return 0;
}


According to top that program eats like 5,7 mbs of RAM.. running that without inserting all that data into the map it eats something like 0,3 mb i think.

any help appreciated..

MTsoul
January 1st, 2007, 11:17 PM
Memory leak only applies if your program doesn't clean unused stuff. I don't see the problem here, since it generates a bunch of stuff and quits right after.

The only thing I'd be worried about is that "new char[10]" thing since you aren't popping everything off the map. But again it doesn't matter all that much if it's done in less than a few seconds.

Al6200
January 2nd, 2007, 07:15 AM
Shouldn't Windows clear your program's data from RAM after it exits? That system makes a lot of sense to me.

Danii
January 2nd, 2007, 09:31 AM
Yes the memory is freed when the program terminates, that's not the problem. it should be freed when i remove all those elements in the map..

The program doesnt quit, it stands still on that cin.get().
That is just a testcode, lemme explain.

in that map i insert 1024*1024 char elements, or pointers to them i guess. tht takes up about 4-5 mb. this is what happens in the first for-loop.

in the second for-loop, it deletes all the elements inserted and after that comes tht cin.get() which just waits for any input, kind of a pause.

during that pause i look up how much memory the program is using and it says 5,7 mb. so the problem is that it isn't freeing those mbs when i clear the map.

Also, im not running windows, but yes all the memory is freed once the program quits, but i want it to be freed when all the elements are removed.

hope u guys understand..

crunchi
June 30th, 2008, 11:30 PM
This is an old thread I know, but just in case someone comes across this like I did.

for(std::map<int, char*>::iterator MapItor = Mappy.begin(); MapItor != Mappy.end(); ++MapItor)
{
char* Value = (*MapItor).second;
delete Value;
}

You are clearing the memory correctly but you aren't erasing the now invalid pointer from the map.
after this loop call something like:

Mappy.clear();

You should see a decrease in the memory used once there aren't like 1,000,000 invalid pointers in memory.
Although I'm sure you figured this out by now...