Find the largest free memory block

Sometimes there is a problem with running out of memory when it is fragmented.

Can I find the largest free memory block? I am using Delphi 2007 with FastMM. Development of a Windows XP application running Windows 2003.

Hi

EDIT: I could add information that the application runs on a server with 32 GB of memory on Windows Server 2003 x64. But the application is a 32-bit application, so the theoretical maximum allocated memory for each instance is 2 GB. Many instances start immediately. I do not think this is a complete physical memory. I think when starting the application received 32-bit virtual memory space. This may be too fragmented at runtime.

I also found a FastGetHeapStatus method that returns a THeapStatus with some fields for free memory. Perhaps I could use them.

EDIT2: I found this How to get the largest available memory block . C code, but maybe it can be translated into Delphi.

+3
source share
3 answers

This is the translation of the Delphi code you wanted:

function GetLargestFreeMemRegion(var AAddressOfLargest: pointer): LongWord;
var
  Si: TSystemInfo;
  P, dwRet: LongWord;
  Mbi: TMemoryBasicInformation;
begin
  Result := 0;
  AAddressOfLargest := nil;
  GetSystemInfo(Si);
  P := 0;
  while P < LongWord(Si.lpMaximumApplicationAddress) do begin
    dwRet := VirtualQuery(pointer(P), Mbi, SizeOf(Mbi));
    if (dwRet > 0) and (Mbi.State and MEM_FREE <> 0) then begin
      if Result < Mbi.RegionSize then begin
        Result := Mbi.RegionSize;
        AAddressOfLargest := Mbi.BaseAddress;
      end;
      Inc(P, Mbi.RegionSize);
    end else
      Inc(P, Si.dwPageSize);
  end;
end;

You can use it as follows:

procedure TForm1.FormCreate(Sender: TObject);
var
  BaseAddr: pointer;
  MemSize: LongWord;
begin
  MemSize := GetLargestFreeMemRegion(BaseAddr);
  // allocate dynamic array of this size
  SetLength(fArrayOfBytes, MemSize - 16);

  Caption := Format('Largest address block: %u at %p; dynamic array at %p',
    [MemSize, BaseAddr, pointer(@fArrayOfBytes[0])]);
end;

, 16 , -, , , , 16.

+4

, "maxavail" Turbo Pascal, , , , .

heapmanager , , , ( ) .

, , , ( ). , windows api.

, , . , - Dos, , .

, ( -) () . ,

, , , winapi , . , .

+6

, . . , .

, . , - , , . , , , , .

, , : , -, AWE (. ) .

1:

C ++. , . :

  • , ( ). , . , , , .

    , , . , ; , , . .

  • , . , , .. . , , , , , .

2: PAE

Windows MMU, , . , , , , 2 .

Windows PAE, API, MMU . .

  • , .

  • , .

, (, - , ). , , PAE, FastMM - , PAE.

- , . ( ) API. - - . , . YMMV.

3:

, (, , , ). , .

, , , . , .

+3

Source: https://habr.com/ru/post/1732833/


All Articles