At EKON 13, last week in Darmstadt, Germany, my partner Daniel Magin held a session about how to debug with Delphi. One of the things he demonstrated, was the usage of Memory Managers for debugging purposes.

Since Delphi 2006 there is a new Memory Manager in Delphi: FastMM4 – which is an Open Source project. That one has many advantages over the old BorlandMM. Especially for server-type applications (such as VCL for the Web / IntraWeb applications) FastMM4 is a must – many problems in IntraWeb applications have their source in the old MemoryManager, which is simlpy not designed to handle large numbers of objects being created and freed. I.e. you should download FastMM4 it if you are still on D2005 or older.

One thing that FastMM4 can help with is detecting Memory Leaks. This has been discussed on many blogs already (look for ReportMemoryLeaksOnShutdown := true;), this is really helpful and can even be configured.

Detecting Memleaks during Debugging is one important thing, but locating code that overwrites memory, or accesses objects that have already been freed is also very important. Consider the following code:

program Project20;

{$APPTYPE CONSOLE}

uses
  //Decomment to find memory errors
  //SafeMMInstall,
  SysUtils,
  Classes;

var
  sl: TSTringList;
  i: Integer;
  j: Integer;
begin
  ReportMemoryLeaksOnShutdown := true;
  try
    sl := TStringList.create;
    i := sl.Count;
    //Free Stringlist by purpose
    sl.Free;
    //...

    //Somewhen later - by accident - access a reference to a freed Stringlist
    j := sl.Count;

    //just do something ...
    if j = i then
      Writeln('j=i')
    else
      Writeln('j<>i');
  except
    on e: Exception do
      WriteLn(e.Message);
  end;
  ReadLn;
end.

It accesses a stringlist’s count property after it has already been freed. In complex Class hierarchies this is a situation that may easily happen.

Memleak detection is turned on, but with D2009 this code will run through just fine. There are possibilities to download  FastMM’s full version and tweak it’s config file to detect this situation.

An other option is to use an other Memory Manager, as Daniel pointed out: SafeMM, which is an Open Source project, hosted at Embarcadero’s CodeCentral. Just put “SafeMMInstall” as very first item into your projects uses clause and it will raise exceptions, every time you do something which would corrupt memory. Now recompile your project and let it run – you “error-free” application might unveil quite some errors now :-)

Use SafeMM only for debugging purposes – it’s memory footprint is about 4x the normal one.

blog comments powered by Disqus
CodeGear Technology Partner