Find memory leaks in Delphi
In my previous jobs I always used Java, when I began to program in Delphi the biggest obstacle was freeing the memory!
I didn’t realized how useful was the Java Garbage Collector until I began to use Delphi! 😯
The best practice to avoid memory leaks in Delphi is to free the memory using a template like this:
myList := TStringList.Create; // Create the Object try ... myList usage ... finally FreeAndNil(myList); // Free the memory end; </pre>
…but obviously this is not always possible 😦
How to find memory leaks
To overcame these problems I found very usefull to set:
ReportMemoryLeaksOnShutdown := True;
It shows a list of memory leaks (if any) when you close the program.
If you want to perform this check only in your debug build, you can use:
{$IFDEF DEBUG} ReportMemoryLeaksOnShutdown := True; {$ENDIF}
If you want to use this check only if you are in Delphi Debug Mode (F9), you can use:
ReportMemoryLeaksOnShutdown := DebugHook <> 0;
Examples:
Following an example of alert caused by TStringList.Create;
…and an example of alert caused by TButton.Create(nil);
Related Links:
Memory Leak Notification in Delphi
Top 4 Memory Leak Fix Tools