Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When is it safe to Dispose a nil pointer?

In the following example:

program DisposeProblem;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  Person = record
    name: string;
    age: Integer;
  end;

var
  p: ^Person;

begin
  p := nil;
  Dispose(nil); // OK
  Dispose(p); // AV
end.

Why is the first Dispose() call OK, while the second causes an access violation error? When I step through the code, the first Dispose() calls System._FreeMem(), while the second calls System._Dispose(), but I don’t understand why this is the case. I would like to understand this behavior so I can know when it is safe to call Dispose() on a nil pointer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would like to understand this behavior so I can know when it is safe to call Dispose() on a nil pointer.

It is never OK to call Dispose() on a nil pointer variable. The RTL will unconditionally try to finalize the object that is being pointed at. Passing in a pointer variable that is nil leads to undefined behavior and will likely crash.

FreeMem() allows a nil pointer as input. Dispose() on a pointer variable does not allow nil, and never has.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading