malloc之后free,再申请Big内存失败.
Cline 2012-02-09 11:04:38 1.调用malloc(64K)多次,直到返回NULL;
2.调用malloc(1M),失败;
3.调用free(64K),释放#1分配的内存.
4.loop #2.
5.释放完#1所有内存, malloc(1M)依然失败.
为什么malloc(1M)不能成功?
Win7, VS2008.
调用HeapCompact(), SetProcessWorkingSetSize()也没用。
#include "malloc.h"
#include < ERRNO.H>
int _tmain(int argc, _TCHAR* argv[])
{
const unsigned int MEM_1_K = 1024;
const unsigned int MEM_64_K = 64 * MEM_1_K;
const unsigned int MEM_MAX = 3 * MEM_1_K * MEM_1_K * MEM_1_K;
int memCount = 0;
void** Mem = new void*[MEM_1_K * MEM_1_K];
unsigned int m = 0;
void* p = NULL;
for(; m < MEM_MAX; ++memCount)
{
p = malloc(MEM_64_K);
if(NULL == p)
{
break;
}
m += MEM_64_K;
if(memCount < (MEM_1_K * MEM_1_K))
{
Mem[memCount] = p;
*(char*)p = 'a';
}
}
::printf("%dk was allocated!", m/MEM_1_K);
//::getchar();
int index = 0;
SIZE_T s;
do
{
p = malloc(MEM_1_K * MEM_1_K);
if(!p)
{
if(index >= memCount)
break;
for(int j = 0; j < 16; j++)
{
if((index < memCount) && Mem[index])
{
free(Mem[index]);
Mem[index] = NULL;
index++;
}
else
{
break;
}
}
s = ::HeapCompact(GetProcessHeap(), 0);
BOOL b = SetProcessWorkingSetSize(GetCurrentProcess(), -1, -1);
if(!b)
{
DWORD dw =::GetLastError();
dw = dw;
}
}
}while(!p);
if(!p)
{
p = ::VirtualAlloc(NULL, MEM_1_K * MEM_1_K, MEM_COMMIT | MEM_RESERVE|MEM_LARGE_PAGES, PAGE_READWRITE);
if(!p)
{
DWORD dw = ::GetLastError();
::printf("Failed to allocate 1M memory!");
::getchar();
}
}
return 0;
}