Fpsonar memory

← Back to fpsonar

Object Pascal outside of interfaces is manual-memory territory: what you Create, you must Free, exactly once, on every path out of the routine. These rules look for the ways that goes wrong. This is the chapter where fpsonar earns its place — the compiler will not help you with any of it.

The one-line summary of the whole chapter: acquire, then try, then release in finally.

CreateWithoutTryFinally

edit

major · off by default

An object created and released in the same statement list, with nothing protecting it, leaks if anything between the two raises. Wrap it.

Note the rule currently reasons within one statement list only, so it sees the simple shape and not yet the leak that hides behind an early exit in a nested branch.

fpsonar complains about this

var
  L: TStringList;
begin
  L := TStringList.Create;
  L.LoadFromFile(AName);        // if this raises, L leaks
  Process(L);
  L.Free;
end;

fpsonar accepts this

var
  L: TStringList;
begin
  L := TStringList.Create;
  try
    L.LoadFromFile(AName);
    Process(L);
  finally
    L.Free;
  end;
end;

OwnedFieldNotFreedInDestructor

edit

major · off by default

If a constructor creates an object and stores it in a field, the destructor is responsible for releasing it. Miss it and every instance of your class leaks one object.

The rule stays silent when the field is released indirectly — by a helper method the destructor calls, by BeforeDestruction, by a loop over an owned list, or when the class declares no destructor of its own — because in those cases it cannot show the field is unreleased.

fpsonar complains about this

constructor TReport.Create;
begin
  inherited Create;
  FLines := TStringList.Create;
end;

destructor TReport.Destroy;
begin
  inherited Destroy;          // FLines never freed
end;

fpsonar accepts this

destructor TReport.Destroy;
begin
  FLines.Free;
  inherited Destroy;
end;

FreeOnInterfaceReference

edit

major · off by default

Interface references are reference-counted: the RTL frees the object when the last reference goes out of scope. Two forms are reported: a hard cast,TObject(R).Free, and FreeAndNil(R).

fpsonar complains about this

var
  R: IReader;
begin
  R := TFileReader.Create;
  R.Read;
  TObject(R).Free;                     // double release
end;

Or fpsonar complains about this

var
  R: IReader;
begin
  R := TFileReader.Create;
  R.Read;
  FreeAndNil(R): // Accepted by previous version of the FPC/Delphi compilers
end;

fpsonar accepts this

var
  R: IReader;
begin
  R := TFileReader.Create;
  R.Read;
end;                          // released automatically

SelfDestroyedInMethod

edit

major · off by default

A method that frees Self leaves its own caller holding a dangling reference, and execution continues in a destroyed object. Legitimate self-destruction exists — a Release pattern — but it is rare enough to be worth a second look every time.

fpsonar complains about this

procedure TJob.Finish;
begin
  DoFinish;
  Free;                       // caller's reference is now dangling
end;

fpsonar accepts this

procedure TJob.Finish;
begin
  DoFinish;
end;

// the owner decides when to release:
Job.Finish;
Job.Free;

NewDisposeMismatch

edit

critical · off by default

Pascal has two allocator pairs and they cannot be mixed: New goes with Dispose, GetMem with FreeMem. New/Dispose also initialise and finalise managed fields; GetMem/FreeMem do not. Crossing them corrupts the heap or leaks the managed parts.

fpsonar complains about this

var
  P: PMyRecord;
begin
  New(P);
  FreeMem(P);                 // wrong deallocator
end;

fpsonar accepts this

var
  P: PMyRecord;
begin
  New(P);
  Dispose(P);
end;

ExceptionObjectFreedInHandler

edit

critical · off by default

The RTL owns the exception object inside a handler and frees it when the handler finishes. Freeing it yourself means it is freed twice.

fpsonar complains about this

except
  on E: Exception do
  begin
    Log(E.Message);
    E.Free;                   // the RTL will free it again
  end;
end;

fpsonar accepts this

except
  on E: Exception do
    Log(E.Message);
end;

RaisedExceptionInstanceReused

edit

major · off by default

raise transfers ownership of the exception object to the exception machinery. Touching the variable afterwards reads an object you no longer own, and which may already be gone.

fpsonar complains about this

var
  E: EConfigMissing;
begin
  E := EConfigMissing.Create('missing');
  raise E;
  Log(E.Message);             // E is no longer yours
end;

fpsonar accepts this

begin
  Log('missing');
  raise EConfigMissing.Create('missing');
end;

LoopVariableUsedAfterLoop

edit

major · off by default

The language does not define what a for loop's control variable holds once the loop finishes — it may be the last value, one past it, or anything else, and it varies with the compiler and optimisation level. Reading it afterwards is code that happens to work.

Known limitation: the rule does not yet notice an assignment between the loop and the read that makes the value well-defined again.

fpsonar complains about this

for I := 1 to Count do
  Process(I);
WriteLn('stopped at ', I);    // I is undefined here

fpsonar accepts this

Last := 0;
for I := 1 to Count do
begin
  Process(I);
  Last := I;
end;
WriteLn('stopped at ', Last);

LoopVariableModifiedInBody

edit

major · off by default

Assigning to a for control variable inside its own body is illegal in Object Pascal — the compiler rejects it in most modes. Where it slips through, the loop's behaviour is undefined. Use a while loop when you need to control the counter.

fpsonar complains about this

for I := 1 to 10 do
begin
  Process(I);
  Inc(I);                     // not allowed
end;

fpsonar accepts this

I := 1;
while I <= 10 do
begin
  Process(I);
  Inc(I, 2);
end;

FreeAndNilArgument

edit

major · on by default

FreeAndNil takes a class instance variable. Passing anything else — a record, an interface, an ordinary pointer — is not what it is for, and on some versions it will happily scribble over the value.

fpsonar complains about this

var
  P: Pointer;
begin
  FreeAndNil(P);
end;

fpsonar accepts this

var
  L: TStringList;
begin
  FreeAndNil(L);
end;

ObjectCastBeforeFree

edit

minor · on by default

Free is declared on TObject, so casting to TObject before calling it achieves nothing.

fpsonar complains about this

TObject(Reader).Free;

fpsonar accepts this

Reader.Free;

ConstructorOnInstanceVariable

edit

major · on by default

Calling a constructor on a variable that already holds an instance re-runs initialisation on the existing object rather than making a new one — and the old contents, including anything it owned, are overwritten in place.

fpsonar complains about this

L := TStringList.Create;
L.Add('a');
L.Create;                     // re-initialises in place

fpsonar accepts this

L := TStringList.Create;
L.Add('a');
L.Free;
L := TStringList.Create;

DestructorShouldOverrideDestroy

edit

major · on by default

Free calls Destroy, virtually. A destructor with another name, or one that is not marked override, is never reached through Free — so your cleanup silently does not run.

fpsonar complains about this

type
  TReport = class
    destructor Cleanup;       // Free will never call this
  end;

fpsonar accepts this

type
  TReport = class
    destructor Destroy; override;
  end;

Paths through a routine

edit

The eight rules below do not look at a statement in isolation — they follow every path through the routine and ask what has been released by the time control reaches a given point. That is why they can tell "freed on one branch" from "freed on all of them".

Because they reason about paths, they are silent when they cannot see the whole picture: a reference handed to another routine, stored in a field, or returned may be released elsewhere, and none of these rules will claim otherwise.

All eight are off by default.

UseAfterFree

edit

major · off by default

A local is read on a path that has already released it. The memory may still look intact, so the symptom is usually corruption somewhere else entirely — which is what makes this worth catching statically.

fpsonar complains about this

lReport := TReport.Create;
try
  lReport.Render;
finally
  lReport.Free;
end;
WriteLn(lReport.Title);        // released above

fpsonar accepts this

lReport := TReport.Create;
try
  lReport.Render;
  WriteLn(lReport.Title);
finally
  lReport.Free;
end;

DoubleFree

edit

major · off by default

A reference is released again with no assignment in between. The second Free runs a destructor on memory that no longer belongs to the object.

FreeAndNil is the usual fix: Free on a nil reference is safe, so nilling makes a second release harmless.

fpsonar complains about this

lReport.Free;
if lFailed then
  lReport.Free;                // already released

fpsonar accepts this

FreeAndNil(lReport);
if lFailed then
  FreeAndNil(lReport);         // Free on nil does nothing

FreeNotFreeAndNilOnField

edit

major · off by default

A field is released with Free and read afterwards. A local going out of scope is one thing; a field outlives the method, so leaving it pointing at released memory arms the problem for the next method that touches it.

fpsonar complains about this

procedure TReport.Reset;
begin
  FBuffer.Free;
  if FBuffer <> nil then      // still points at released memory
    FBuffer.Clear;
end;

fpsonar accepts this

procedure TReport.Reset;
begin
  FreeAndNil(FBuffer);
  if FBuffer <> nil then
    FBuffer.Clear;
end;

LeakOnEarlyExit

edit

major · off by default

An Exit or raise is reached while a constructed local is still unreleased. The happy path frees it and the early one does not — the classic shape of a leak that only shows up under error conditions, which is exactly when it is hardest to reproduce.

fpsonar complains about this

lReport := TReport.Create;
if not lReport.Load(aFile) then
  Exit;                        // leaks
lReport.Render;
lReport.Free;

fpsonar accepts this

lReport := TReport.Create;
try
  if not lReport.Load(aFile) then
    Exit;
  lReport.Render;
finally
  lReport.Free;
end;

StreamNotProtected

edit

major · off by default

A stream constructed into a local with no try..finally covering the construction. Streams hold an operating-system handle, so leaking one costs more than memory — the file stays open and, on Windows, locked.

fpsonar complains about this

lStream := TFileStream.Create(aName, fmOpenRead);
lStream.Read(lBuffer, lCount);      // an exception here leaks the handle
lStream.Free;

fpsonar accepts this

lStream := TFileStream.Create(aName, fmOpenRead);
try
  lStream.Read(lBuffer, lCount);
finally
  lStream.Free;
end;

GetMemWithoutFreeMem

edit

major · off by default

A heap allocation into a local that no path of the routine releases. The manual-memory counterpart of a missing Free.

fpsonar complains about this

GetMem(lBuffer, lSize);
Process(lBuffer, lSize);

fpsonar accepts this

GetMem(lBuffer, lSize);
try
  Process(lBuffer, lSize);
finally
  FreeMem(lBuffer);
end;

ObjectCreatedInLoopNotFreed

edit

major · off by default

A construction inside a loop body that the loop does not release. One leak per iteration, so unlike most leaks this one scales with the input and turns into a visible problem.

fpsonar complains about this

for i := 0 to aCount - 1 do
  begin
  lItem := TItem.Create;
  lList.Add(lItem.Name);        // nothing releases lItem
  end;

fpsonar accepts this

for i := 0 to aCount - 1 do
  begin
  lItem := TItem.Create;
  try
    lList.Add(lItem.Name);
  finally
    lItem.Free;
  end;
  end;

Adding the object to a list that owns it is equally fine — then the list is what releases it.

UnbalancedPair

edit

major · off by default · parameter: targets

An acquire whose matching release the routine makes outside a covering try..finally. The release exists, so this is not a leak in the straight-line case; it becomes one the moment anything between the two raises.

Unlike the rules above, this one is not about Create/Free specifically. It is driven by a targets parameter naming the acquire/release pairs you care about, so it can be pointed at any paired API — InitCriticalSection/DoneCriticalSection, BeginUpdate/EndUpdate, Lock/Unlock, a library's Open/Close.

fpsonar complains about this

lList.BeginUpdate;
Rebuild(lList);                 // a raise here never reaches EndUpdate
lList.EndUpdate;

fpsonar accepts this

lList.BeginUpdate;
try
  Rebuild(lList);
finally
  lList.EndUpdate;
end;
edit

try..finally shapes, and the rules about acquiring inside the try, are in exceptions. Casts that produce a pointer into a temporary are in strings. Rules that follow values rather than lifetimes — assignments nothing reads, variables read before they are set — are in values through a routine.

See also

edit
  • fpsonar — what fpSonar is, and how to run it

← Back to fpsonar