X86 application. For the next code

void *a = VirtualAlloc(0, 0x14000000, MEM_RESERVE, PAGE_READWRITE); void *b = VirtualAlloc(0, 0x8000000, MEM_RESERVE, PAGE_READWRITE); void *c = VirtualAlloc(0, 0x18000000, MEM_RESERVE, PAGE_READWRITE); 

"sometimes" c equals 0 GetLastError() == 8 (ERROR_NOT_ENOUGH_MEMORY), therefore, the application cannot continue its work and terminates. It is treated by rebooting the system.

If you do not restart and swap the first and third lines, everything will work fine. Re-exchange necessarily leads to the same problem. What are the reasons why the code can not work?

  • The size of the RAM does not matter, because you allocate virtual memory. - VladD
  • Well, you allocate half a gigabyte of memory, depending on how the structures already allocated at this point are located, there may not be enough space. Do not forget, the Yuzermodov process memory in x86 is limited to two gigabytes. It may be trite not to find a free piece of suitable length. - VladD

1 answer 1

You are trying to allocate three continuous pieces of memory with the size of 320, 128, 384 megabytes. When you bite off 320 and 128, then a continuous piece of 384 megabytes may not be. Whereas with the allocation of 320 and 384 megabytes, the chance to find a continuous piece of 128 megabytes is much higher (three times). If you really need such amounts of memory, then reserve everything at once in one piece. And then cut as you need

 void *a = VirtualAlloc(0, (320 + 128 + 384) * 1024 * 1024, MEM_RESERVE, PAGE_READWRITE); void *b = (char*)a + 320 * 1024 * 1024; void *c = (char*)a + 128 * 1024 * 1024; 
  • And if misfortune happened and there is not enough space for a large piece? .. - T-Max
  • Can the system come up with something else or just say "sorry, I can't"? - T-Max
  • @ T-max did not understand the question. If you need a memory and the system has it, you will get it. If not, do not get it. What else can a system come up with? - Anton Shchyrov