开发者

Why system allocs more memory when using pointers Windows?

I use HeapAlloc to alloc a huge amount of memory, like 400 MB, but when i check the Memory Usage of my program it really uses like 1 GB.

//configuraciones.h
#define ANCHO_MUNDO 5000
#define ALTO_MUNDO 5000

//unidades.cpp
unidad* unidades_memoria = (unidad*)HeapAlloc(heap,  //User Heap
         NULL,ANCHO_MUNDO*ALTO_MUNDO*sizeof unidad);

unidad*** unidades = new unidad**[ANCHO_MUNDO];   //Default Heap
for(int i = 0; i < ANCHO_MUNDO;i++)
    unidades[i] = new unidad*[ALTO_MUNDO];

unidad* actual = unidades_memoria;
unsigned int id = 0;

I debuged my program and I realized that the memory usage icreases when this code is executed开发者_Python百科

for (int y = 0; y < ALTO_MUNDO;y++)
  for (int x = 0; x < ANCHO_MUNDO;x++)
  {
    unidades[x][y] = actual;
    actual++;
    unidades[x][y]->id = id;
    id++;
    unidades[x][y]->dueño = 0;
    memset(&unidades[x][y]->addr,0,sizeof(unidades[x][y]->addr));
  }

Why is this happening??


When you allocate memory, you get all of the virtual address space right away, but it doesn't get mapped into physical memory until you actually write to each page. When you write to a page for the first time, it generates a page fault, and at which point the OS will map in a physical page of memory and restart the operation that generated the page fault.

It does this as an optimization—if it turns out that your program allocates a huge amount of memory but only ever uses a small portion of it, the OS never has to map physical memory, and your program can just pretend as if it has all of that memory.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜