2

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

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??

felknight
  • 1,383
  • 1
  • 9
  • 25
  • What are the declarations of unidad, ANCHO_MUNDO and ALTO_MUNDO? You might be asking for more memory than you think you are but that's hard to figure out without seeing the declarations of the types and macros. – Timo Geusch Aug 14 '11 at 04:21

1 Answers1

1

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.

Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • And the huge amout of memory usage extra is like an index or something that is created by the operative system?? – felknight Aug 14 '11 at 04:18