delphidelphi-2010fastmm

How to RegisterExpectedMemoryLeak?


Let's start with this simple Delphi 2010 snippet:

var
  StringList: TStringList;
begin
  ReportMemoryLeaksOnShutdown := True;
  StringList := TStringList.Create;
  StringList.LoadFromFile('c:\fateh.txt');
  RegisterExpectedMemoryLeak(StringList);

FastMM4 report the memory leak again and again even with Addr(StringList) as parameter so how to Register Expected MemoryLeak and why the methods sitting above doesn't work thank's in advance.


Solution

  • You only registered the leak of the string list object. You also need to register that you are leaking all the objects owned by the string list. In this case it owns StringList.Count instances of string objects. The memory manager does not know that those strings are owned by the string list object and so will also be leaked.

    And that's much easier said than done. Because you need to find the start of the memory block that represents a string. That's at a fixed offset from the string's first character, and the offset depends on which Delphi version you use.

    In Unicode Delphi, in 32 bit code, the offset is 12 bytes. So the following will register the leaked strings:

    for i := 0 to StringList.Count-1 do 
      if StringList[i]<>'' then
        RegisterExpectedMemoryLeak(PByte(StringList[i])-12);
    

    Even when you do that you'll still get two reported memory leaks. At least one of those is explained by the dynamic array that is owned by the string list, TStringList.FList. If you wanted to register that leak, then you'll need to do some more hacking because again you'll have to rely on implementation details as to where that array is stored.