STL MAP内存释放测试
测试过程:
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_tuiUserId;//Systematic distribution id for every UserPhone;uint8_tucFlag;//first send flag:0,no send;1,senduint8_tucAlter;//user can send msg:0,no;1,yescharszUserPhone[14];//user phone numberuint32_tuiLastestBscID;uint32_tuiLastestAreaID;time_tuiMonthBeginTime;//cur month send num begin timetime_tuiLastestSendTime;//last send welcome sms timetime_tuiFirstSendTime;//first send welcome sms timeuint16_tusDaySendNum;//send count every dayuint16_tusMonthSendNum;//send count every monthuint16_tusTotal;//send total countuint32_tuiAreaList[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,结论类似。