Delphi: unexpected memory leak has occured

670 Views Asked by At

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?

3

There are 3 best solutions below

0
Michael Hutter On BEST ANSWER

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

1
Germán Estévez -Neftalí- On

There are some tools that can help you to find memory leaks (AQTime, EurekaLog,...).

Example. See EurekaLog, download the demo/trial and test it. This tools can give you some information about leaks and detailed information about the source code that produce it.

enter image description here

"Detailed info" (including debug information in your application) can help you detect line of error:

enter image description here

0
Artem Razin On

Use one of the memory profilers for Delphi to get call stacks for your leaks:

After reviewing call stacks, you have a chance to understand which objects are leaking.