On the reference counting bugs in Delphi


Delphi allows to access an object instance via object reference and interface reference at the same time. Consider this code:

program RefCounts;



procedure Test;
  Obj: TInterfacedObject;
  II: IInterface;

  Obj:= TInterfacedObject.Create;
  Writeln(Obj.RefCount);             // 0
  II:= Obj;
  Writeln(Obj.RefCount);             // 1
  II:= nil;
// here Obj is already destroyed and we can't reference it anymore
//  Writeln(Obj.RefCount);


Nasty thing is that a reference-counted object is created with zero reference counter and can be destroyed by means of an interface reference. Needless to say that combining object and interface references is bad practice and should be avoided. Unfortunately the reference counting (with zero counters allowed) appeared to be a difficult problem for the compiler too and resulted in compiler bugs even when the code compiled does not use object references (see example here). The bugs were getting fixed with newer Delphi versions but nobody can say which Delphi version is free from them.

Numerics for Delphi & FPC


I “officially” released first beta version of my multiple-precision integer arithmetic implementation – Numerics050. The project taken more time than I expected but now the design (I hope) become stable.

All that is needed to use BigCardinal and BigInteger types with Delphi or Lazarus/FPC is a single pascal unit Numerics.pas and a single dll (numerics32.dll for 32-bit Windows and numerics64.dll for 64-bit Windows). Both dll are built by FPC 2.6.2 and contain pure Pascal code without assembler optimization.

The archive also contains console application PiBench (for Delphi and Lazarus) which demonstrates how to use BigCardinal and BigInteger types (not much different from plain old Cardinal and Integer types).

The software contained in the archive (compiled dll’s numerics32.dll and numerics64.dll, dll wrapper unit Numerics.pas and demo benchmark application PiBench) is free and released under MIT license.