# \[C++\] clearing a map?

**URL:** <https://forum.kirupa.com/t/c-clearing-a-map/211472>\
**Category:** programming\
**Created:** [January 2, 2007, 2:05am UTC](https://forum.kirupa.com/t/c-clearing-a-map/211472 "2007-01-02T02:05:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Danii](https://avatars.discourse-cdn.com/v4/letter/d/c67d28/32.png) [@Danii](https://forum.kirupa.com/u/Danii)\
**Post date:** [January 2, 2007, 2:05am UTC](https://forum.kirupa.com/t/c-clearing-a-map/211472/1 "2007-01-02T02:05:31Z")

</div>

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.

```auto

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…

---

<div class="post-metadata">

**Author:** ![crunchi](https://avatars.discourse-cdn.com/v4/letter/c/82dd89/32.png) [@crunchi](https://forum.kirupa.com/u/crunchi)\
**Post date:** [July 1, 2008, 2:30am UTC](https://forum.kirupa.com/t/c-clearing-a-map/211472/2 "2008-07-01T02:30:36Z")

</div>

This is an old thread I know, but just in case someone comes across this like I did.

```
for(std::map&lt;int, char*&gt;::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…

---

<div class="post-metadata">

**Author:** ![Spetertoi](https://avatars.discourse-cdn.com/v4/letter/s/a9adbd/32.png) [@Spetertoi](https://forum.kirupa.com/u/Spetertoi)\
**Post date:** [July 5, 2008, 4:23pm UTC](https://forum.kirupa.com/t/c-clearing-a-map/211472/3 "2008-07-05T16:23:11Z")

</div>

Happiness takes no account of time.**　　　 /　./　/\_　　 I Hand You　 {^\_ _}_　 )　}/^&#12288;　　 A Rose…　/　/\_/^._}_/　//　/ (　({(@)}\__}.//_/A\_\_\_A[wow gold\_\_\_\_A\_\_[url=http://www.comegames.com/gamecy.jsp]wow gold](http://www.comegames.com/)_A\_\_\_\_\_\_A_\_\_\_　\__/{/(_)\_}　)\ \—v----V-----V–Y----v—Y-----　　(　 (\_\_)_)_/　)\ &gt;　　　　 \ __/　　 \__ ///**
