操作系统何时释放内存?当我使用性能计数器时,我没有看到它被删除。请参阅下面的代码。 分配之前的内存使用情况和解除分配之后的内存使用情况之间的差异应该是0但不是。 基本上,我有一个DLL 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;
}
简单:只是不创建泄漏 – ckv