Search code examples
delphimemoryvirtualmemory-leaks

Why is my program leaking Virtual Memory?


In search of memory leak, I have been using MemProof and be able to see live counts of resources being used, created and destroyed. After having run my program for over a day and half, I have noticed that everything else being constant or less, Virtual Memory (VM) is increasing in counts. It started out at 109 and now it is at 113 after 24 hours.

This is what MemProof says for each VM leak:

VirtualAlloc(address_location, 16384, 4096, 4); It is identified as Virtual Memory and its size is always 16384. API name is VirtualAlloc. The module is kernel32.dll.

Furthermore, memproof says, "virtualalloc reserves or commits a region of pages in the virtual address space of the calling process. Allocated pages must be freed with virtualFree when no longer needed."

VM leak is associated with a function in the file System.Pas.

The function is as follows:

function GetCmdShow: Integer;
var
  SI: TStartupInfo;
begin
  Result := 10;                  { SW_SHOWDEFAULT }
  GetStartupInfo(SI);
  if SI.dwFlags and 1 <> 0 then  { STARTF_USESHOWWINDOW }
    Result := SI.wShowWindow;   
end;  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

I have the less than signs pointing at the key word "end" is where Memproof takes me to when I click on virtual memory leak(s).

So, what does this mean?


Solution

  • Delphi's FastMM memory manager works on top of the Windows memory system. It allocates large blocks of memory from the OS with VirtualAlloc, and then divides that up into smaller chunks for your program to work with. If you free large amounts of memory, it will give some of it back to the OS. If you free small amounts of memory, though, it's likely to hold on to it because you're likely to need it again soon. This is part of what makes FastMM fast, and it's not a memory leak.

    Any memory profiler that only watches VirtualAlloc and doesn't actually pay attention to what FastMM is doing is going to give you results that don't make sense. As David mentioned in the comment, if you want to track down real memory leaks, you need to use the FastMM tools. Download the full version of FastMM from SourceForge and read the documentation to find out how to enable FullDebugMode and leak reporting and logging, and you'll have a much easier time of it.