RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.Dispose Function

Releases memory allocated for a dynamic variable.

Pascal
procedure Dispose(var P: Pointer);
C++
Dispose(void * P);

System

Use Dispose in Delphi code to free the memory which a pointer addresses. After a call to Dispose, the value of P is undefined and it is an error to reference P.

Note: If compiling with {$I+}, use exceptions to handle this error. When an invalid pointer is passed to Dispose it raises an EInvalidPointer exception.
 

Delphi Examples: 

 

{
The following code explicitly allocates memory for a pointer
in the OnCreate event of Form1, then releases the memory in
the OnDestroy event. Assume that MyPtr is a Pointer type
field of TForm1.
} 
procedure TForm1.FormCreate(Sender: TObject);
begin
  New(MyPtr);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Dispose(MyPtr);
end;
{
The following code adds an object to MyList if it isn’t
already in the list.
}
type
  PMyList = ^AList;
  AList = record
    I: Integer;
    C: Char;
  end;
var
  Form1: TForm1;
  MyList: TList;
  ARecord1, ARecord2: PMyList;

implementation

{$R *.dfm}

procedure DisplayTList(TheList: TList);
var
  ARecord: PMyList;
  B: Byte;
  Y: Word;
begin
    { Now paint the items onto the paintbox}
    Y := 10;             {Variable used in TextOut function}
    for B := 0 to (TheList.Count - 1) do
    begin
      ARecord := TheList.Items[B];
      Form1.PaintBox1.Canvas.TextOut(10, Y, IntToStr(ARecord^.I)); {Display I}
      Y := Y + 30;  {Increment Y Value again}
      Form1.PaintBox1.Canvas.TextOut(10, Y, ARecord^.C);  {Display C}
      Y := Y + 30;  {Increment Y Value}
    end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if (MyList.IndexOf(ARecord1) = -1) then MyList.Add(ARecord1);
  DisplayTList(MyList);
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  if (MyList.IndexOf(ARecord2) = -1) then MyList.Add(ARecord2);
  DisplayTList(MyList);
end;

procedure TForm1.Button3Click(Sender: TObject);
var
  ARecord: PMyList;
  B: Integer;
begin
  if (MyList.Count <> 0) then
  begin
    for B := (MyList.Count - 1) downto 0 do
    begin
      ARecord := MyList.Items[B];
      MyList.Remove(ARecord);
    end;
  end;
  Form1.PaintBox1.Repaint;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  MyList := TList.Create;
  New(ARecord1);
  ARecord1^.I := 100;
  ARecord1^.C := 'Z';
  New(ARecord2);
  ARecord2^.I := 200;
  ARecord2^.C := 'X';
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Dispose(ARecord1);
  Dispose(ARecord2);
  MyList.Free;
end;

 

EInvalidPointer 

FreeMem 

GetMem 

New

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!