Delete memory of std::map<int, string> completely
Solution 1
The way to do it right is not to do it. A map
will automatically release resources when it's destroyed for anything allocated automatically.
Unless you allocated the values with new
, you don't delete
them.
{
std::map<short,std::string> x;
x[0] = "str";
}
//no leaks here
{
std::map<short,std::string*> x;
x[0] = new std::string;
delete x[0];
}
Solution 2
Simply call map.clear();
. This will release all objects the map has allocated internally.
Note that in system tools like the task manager, your application can still show the same amount of memory occupied. It's perfectly possible the OS decides not to reclaim the memory your process once held, in case it allocated it again. It would reclaim it later if it started to run short.
skylla
Updated on February 15, 2022Comments
-
skylla about 2 years
I have a map filled with and now I want to delete the memory completely. How do I do this right? couldn't find anything specific for this topic, sorry if it is already answered...
my code is something like this:
for(std::map<short,std::string>::iterator ii=map.begin(); ii!=map.end(); ++ii) { delete ⅈ }
But it doesnt work. Can anybody help pls?
regards, phil
-
skylla about 11 yearsMy map is filled like this: map[0] = "someString"; and it still gives me Mem-Leaks! if i dont use the map in my program, i dont have any leaks, so it must be the map i guess..
-
Angew is no longer proud of SO about 11 years@user1971024 How do you know it has mem-leaks?
-
Babak about 11 years@LuchianGrigore nice opening. THNX
-
David Mokon Bond about 11 yearsWhile anything is possible std::map probably doesn't have a memory leak. Can you post some more code giving usage. Is the map on the heap as well?
-
skylla about 11 yearsThanks for your answer, but this didnt help either. Still the same MemoryLeak
-
skylla about 11 yearsMy map is created in a static Function via 'std::map<short, std::string> map; ' then it is filled via 'map[0] = "someString";' and then it is deleted via 'map.clear()'
-
juanchopanza about 11 years@user1971024 then the leak is coming from somewhere else, or there is no leak at all.
-
Yunnosch over 2 yearsWelcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
-
zkoza over 2 yearsOP asked explicitly about
std::map<int, string>
. Your answer addresses a completely different problem of maps into naked pointers into heap-allocated resources, something modern C++ should avoid.