---
title: "STL MAP内存释放测试"
author: "axengine"
date: "2011-12-03T16:07:42Z"
tags: []
categories: ["编程语言"]
slug: "stl-map"
draft: false
lastmod: "2011-12-03T16:07:56Z"
id: 1290577
url: "https://snmp.iteye.com/blog/1290577"
---

测试过程：

insert采用malloc分配内存，释放时采用free释放内存，并erase操作子。使用top窗口查看程序使用的内存。

测试结果：

free后，操作系统为程序分配的内存并不会free掉，而被Hold了。当再次调用insert入map，会使用未free掉的内存。

如果后面insert同样采用malloc分配内存，操作系统会优先使用先去malloc且free掉的内存，若不够再malloc新内存。

测试代码如下：

 

```
#include <iostream>
#include <map>
#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
#pragma pack(1)
typedef struct
{
	uint32_t	uiUserId;					//Systematic distribution id for every  UserPhone;
	uint8_t		ucFlag;						//first send flag:0,no send;1,send
	uint8_t		ucAlter;					//user can send msg:0,no;1,yes
	char		szUserPhone[14];			//user phone number
	uint32_t	uiLastestBscID;				
	uint32_t	uiLastestAreaID;
	time_t		uiMonthBeginTime;			//cur month send num begin time
	time_t		uiLastestSendTime;			//last send welcome sms time
	time_t		uiFirstSendTime;			//first send welcome sms time
	uint16_t	usDaySendNum;				//send count every day
	uint16_t	usMonthSendNum;				//send count every month
	uint16_t	usTotal;					//send total count	
	uint32_t	uiAreaList[5];	
}CUserInFile;
#pragma pack()
#define LEN sizeof(CUserInFile)
typedef map<int,CUserInFile*> UserMap;
UserMap userMap;
int main()
{
	FILE *fp;
	char buff[LEN];
	int i=0;
	fp=fopen("userprofile_wifi","r");
	memset(buff,0x00,LEN);
	while(fread(buff,1,LEN,fp)==LEN)
	{
		fseek(fp,SEEK_CUR,LEN);
		//fwrite(buff,LEN,10,fpw);
		CUserInFile* pUser=(CUserInFile*)malloc(LEN);
		userMap.insert(make_pair(i++,pUser));
	}
	fclose(fp);
	//fclose(fpw);
	printf("insert ok:%d\n",i);
	getchar();
	UserMap::iterator it;
	for(it=userMap.begin();it!=userMap.end();++it)
	{
		if(it->second==NULL)
		{
			printf("dasdsadas\n");
			continue;
		}
		CUserInFile* pUser=it->second;
		free(pUser);
		userMap.erase(it);
	}
	printf("free ok\n");
	getchar();
	fp=fopen("userprofile_wifi","r");
	memset(buff,0x00,LEN);
	while(fread(buff,1,LEN,fp))
	{
		fseek(fp,SEEK_CUR,LEN);
		CUserInFile* pUser=(CUserInFile*)malloc(LEN);
		userMap.insert(make_pair(i++,pUser));
	}
	fclose(fp);
	printf("insert again ok\n");
	getchar();
	return 0;
}
```

 后面测试了HASH\_MAP，结论类似。