Can you find this Delphi coding error (part 4)?

Can you spot the error in the following Delphi code?


unit Worker;

interface

uses
  Classes, WorkUnit;

type
  TBaseClass = class
  private
    FList : TList;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Process; virtual;
    property List : TList read FList write FList;
  end;
  
  TChildClass = class(TBaseClass)
  private
    FChildList : TList;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Process; override;
  end;

implementation

constructor TBaseClass.Create;
begin
  inherited Create;
  FList := TList.Create;
end;

destructor TBaseClass.Destroy;
begin
  FList.Free;
  inherited Destroy;
end;

procedure TBaseClass.Process;
begin
  WorkUnit.DoSomeWork(Self);
end;

constructor TChildClass.Create;
begin
  inherited Create;
  FChildList := TList.Create;
end;

destructor TChildClass.Destroy;
begin
  FChildList.Free;
end;

procedure TChildClass.Process;
begin
  WorkUnit.DoSomeOtherWork(Self);
end;

end.

This was quite easy, right?

Solution: The destructor in TChildClass does not call its inherited destructor. The object will not be destroyed properly which at least will result in a memory leak. There should be a last line "inherited Destroy;" in TChildClass.Destroy.

Not so hard to spot! But imagine finding this problem among thousands of lines of code spread over hundreds of units! And consider also a code base that is evolving all the time, so the code must constantly be rechecked.

The good news is that with Pascal Analyzer, our popular static code analyzer, you can automatically find these and many other kinds of coding issues. This particular error above is detected by the Warnings Report, in a section WARN15 "Constructors/destructors without calls to inherited".

Pascal Analyzer has a total of 53 reports. Those are divided into roughly 200 sections, all providing statistics, references, errors and warnings for your code. Pascal Analyzer can be run as a standalone Windows application, or as a command-line program. The second choice is suitable if you want to integrate static code analysis with your build process.

Or use Pascal Expert, our RAD Studio plugin, to find the problems immediately while coding. Pascal Expert contains much of the same capabilities like Pascal Analyzer, and is obtainable with a discount when buying both products.

See our orders page for more details or get free evaluations from the download page.