Skip to content

Detect use of uninitialised memory in finally blocks #216

Open
@zaneduffield

Description

@zaneduffield

Prerequisites

  • This improvement has not already been suggested.
  • This improvement should not be implemented as a separate rule.

Rule to improve

VariableInitialization

Improvement description

An anti-pattern in Delphi is

try
  Foo := TFoo.Create;
  {more code}
finally
  Foo.Free;
end;

which is problematic because if TFoo.Create throws an exception then Foo will be uninitialised when the finally block is executed.

The correct version of that code is

Foo := TFoo.Create;
try
  {more code}
finally
  Foo.Free;
end;

but another correct version would be

Foo := nil;
try
  Foo := TFoo.Create;
  {more code}
finally
  Foo.Free;
end;

In order to catch the issue in the first example, without creating a false positive in the last example, the rule would need to have a better understanding of control flow.

There is an endless supply of similar cases that would benefit from enhanced control flow analysis; this rule improvement isn't really about the try-finally anti-pattern specifically.

Rationale

The current variable initialisation rule is quite rudimentary and fails to catch many common cases of uninitialised memory.
It's too permissive, because it has little-to-no understanding about code structure and control flow.

One of the real benefits of static analysis tools is that they can detect issues that are subtle, and only become apparent after excruciatingly evaluating all the logical paths.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementImprovements to an existing featureruleImprovements or additions to rules

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions