操作系统何时释放内存?当我使用性能计数器时,我没有看到它被删除。请参阅下面的代码。分配前的内存使用量和取消分配后的内存使用量之间的差异应该是 0 但不是。
基本上我有一个托管在 dllhost 中的 COM dll,它会泄漏内存(在 32 位 MS-OS 上超过 2GB)。
#include "stdafx.h"
#include <stdlib.h>
#include <crtdbg.h>
#include <list>
#include <map>
//#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
using namespace std;
/*
#ifdef _DEBUG
#ifndef DBG_NEW
#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )
#define new DBG_NEW
#endif
#endif // _DEBUG
*/
template <class K, class T, class Pr = less<K>, class A = allocator<T> >
class CTypedHeapPtrMap : public map<K, T, Pr, A >
{
public:
// Construction
CTypedHeapPtrMap()
{
};
// Destructor
~CTypedHeapPtrMap()
{
DeleteContents();
};
void DeleteContents()
{
iterator ItEntry;
/* Empty the list and delete memory */
ItEntry = begin();
while (ItEntry != end())
{
T pT = ItEntry->second;
delete[] pT;
pT = NULL;
ItEntry++;
}
map<K,T,Pr,A>::clear();
};
};
typedef CTypedHeapPtrMap<long, char*> VALIDATION_MAP;
int _tmain(int argc, _TCHAR* argv[])
{
PROCESS_MEMORY_COUNTERS_EX pmcx = {};
pmcx.cb = sizeof(pmcx);
GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx), pmcx.cb);
//assumuing GetProcessMemoryInfo call above allocates some memory. So get the memory status again
pmcx.cb = sizeof(pmcx);
GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx), pmcx.cb);
printf(" Memory usage (Before allocation) = %ld\n", pmcx.WorkingSetSize);
{
VALIDATION_MAP pStr;
char *ptr1 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(1, ptr1));
char *ptr2 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(2, ptr2));
char *ptr3 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(3, ptr3));
char *ptr4 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(4, ptr4));
char *ptr5 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(5, ptr5));
char *ptr6 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(6, ptr6));
char *ptr7 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(7, ptr7));
char *ptr8 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(8, ptr8));
char *ptr9 = new char[10000];
pStr.insert(VALIDATION_MAP::value_type(9, ptr9));
}
pmcx.cb = sizeof(pmcx);
GetProcessMemoryInfo(GetCurrentProcess(),reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&pmcx), pmcx.cb);
printf(" Memory usage (After de-allocation) = %ld\n", pmcx.WorkingSetSize);
Sleep(60000);//sleep for a minute
return 0;
}