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

Can you spot the error in the following (somewhat artificial) Delphi code?


program ResultMaker;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type  
  IResultMaker = interface
    function CalcResult : Integer;
  end;
  
  TResultMaker = class(TInterfacedObject, IResultMaker)
  public
    function CalcResult : Integer;
  end;

  function TResultMaker.CalcResult : Integer;
  begin
    // ..
	// ..
  end;
  
  procedure DisplayResult;
  var
    ResultMaker : IResultMaker;
  begin
    ResultMaker := TResultMaker.Create;
	
	try
	  Writeln('Result: '+IntToStr(ResultMaker.CalcResult));
	finally
	  FreeAndNil(ResultMaker);
	end;
  end;
  
begin
  DisplayResult;
end.

This was quite easy, right?

Solution: This code will most probably result in a runtime error (access violation). The reason is that FreeAndNil is passed an interface. However, the compiler will not complain. Also, the code does not make sense at all, because the ResultMaker variable is reference-counted and will be freed automatically. So no need to call FreeAndNil.

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 WARN56 "Parameter to FreeAndNil is not an object".

Pascal Analyzer has a total of 53 reports. Those are divided into over 230 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.