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

Can you spot the error in the following (rather constructed) Delphi code extract?

..
type
  TMyClass = class
    procedure MyMethod;
  end;
  
  procedure TMyClass.MyMethod;
  begin
  end;
  
function AnyFound : Boolean;
begin
  ..
end;  
  
function GetObj : TMyClass;
begin
  if AnyFound then
    Result := TMyClass.Create
  else
    Result := nil;
end;  

..

procedure MainProc;
var
  Obj : TMyClass;
begin
  Obj := GetObj;
  
  try
    Obj.MyMethod; 
	..
  finally
    Obj.Free;
  end;
end;
  
..

This was quite easy, right?

Solution: The object Obj in MainProc is set to the result of a call to GetObj. The problem is that GetObj may return nil, which makes the following call Obj.MyMethod invalid, and will probably result in an access violation.

The good news is that with Pascal Analyzer, our popular static code analyzer product, these situations can be detected automatically. There is a section STWA5 in the Strong Warnings Report. It is called "Possible bad pointer usage".

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.

Pascal Analyzer currently 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.

Can you see the Delphi coding error? (Part 11)
Can you see the Delphi coding error? (Part 10)
Can you see the Delphi coding error? (Part 9)
Can you see the Delphi coding problem? (Part 8)
Can you see the Delphi coding error? (Part 7)
Can you see the Delphi coding error? (Part 6)
Can you see the Delphi coding error? (Part 5)
Can you see the Delphi coding error? (Part 4)
Can you see the Delphi coding error? (Part 3)
Can you see the Delphi coding error? (Part 2)
Can you see the Delphi coding error? (Part 1)