首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VC/MFC >

malloc之后free,再申请Big内存失败.该怎么处理

2012-03-20 
malloc之后free,再申请Big内存失败.1.调用malloc(64K)多次,直到返回NULL2.调用malloc(1M),失败3.调用fre

malloc之后free,再申请Big内存失败.
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;
}


[解决办法]
用 new delete 试试
[解决办法]
没有连续的内存块?
[解决办法]
估计内存产生碎片,或者系统还没有清理出空间来

热点排行