delphimemory-leaksdelphi-10.1-berlinmemory-leak-detector

Delphi: unexpected memory leak has occured


In Delphi I have configured to report memory leaks:

  {$IFDEF Debug}
  ReportMemoryLeaksOnShutdown := true;
  {$ENDIF}

After exiting the program I get the following message:
enter image description here

My program is very big and I have no clue how to find the TStringList which I have created but not freed.
Unfortunately Delphi has no garbage collector...

If I search in my project for TStringList I find ~500 occurences. It doesn't make any sense to check all of them.

How can I find the variable which I forgot to free?


Solution

  • The following software helps to hunt memory leaks:
    https://github.com/shadow-cs/delphi-leakcheck

    Here the steps to follow:

    1. cd C:\Delphi
      git clone https://github.com/shadow-cs/delphi-leakcheck
    2. Add the path C:\Delphi\delphi-leakcheck\Source to your Delphi library path (Tools/Options/...)
    3. Add the following code at the beginning of your MyProject.dpr file:

    Code:

    uses
      // LeakCheck, // Does not need do be defined here (LeakCheck.Report will do it) unless you want to reference it from the DPR
      LeakCheck.Report, // Me first! - I don't have any dependencies but LeakCheck so I finalize after all other units
      LeakCheck.Setup.Trace, // (Optional) Then me - Run setup to configure stack tracing for us
      LeakCheck.Report.FileLog, // Then me - I'm the one that pulls some dependencies and have all the functionality
    
    1. Compile and start your program
    2. Exit your program regularly
      Exiting may need up to several minutes (be patient...)
    3. You will get a message box that tells you that a file C:\Delphi\MyProject\MyProject.log was created.
      This log file contains the name of the function (and its callstack) where the variable was created. It's not the name of the unfreed variable, but at least the function and line number inside this function.

      enter image description here

    This approach solved my problem within several minutes.
    Bonus: this software is completely free - you don't have to pay anything for it