RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
System.FreeMem Function

FreeMem frees a memory block.

Pascal
procedure FreeMem(var P: Pointer); overload;
procedure FreeMem(var P: Pointer; Size: Integer); overload;
C++
FreeMem(void * P);
FreeMem(void * P, int Size);

System

GetMem allocates a block on the heap. To dispose of the buffer, use FreeMem.

Note: FreeMemory is the C++ compatible version of FreeMem.
 

Delphi Examples: 

 

{
The following example uses a button, a string grid, and an
Open dialog box on a form. When the button is clicked, the
user is prompted for a filename. When the user clicks OK,
the specified file is opened, read into a buffer, and closed.
Then the buffer is displayed in two columns of the string
grid. The first column contains the character values in the
buffer. The second column contains the numeric values of the
characters in the buffer.
} 
procedure TForm1.Button1Click(Sender: TObject);
var
  iFileHandle: Integer;
  iFileLength: Integer;
  iBytesRead: Integer;
  Buffer: PChar;
  i: Integer;
begin
  if OpenDialog1.Execute then
  begin
    try
      iFileHandle := SysUtils.FileOpen(OpenDialog1.FileName, fmOpenRead);
      iFileLength := SysUtils.FileSeek(iFileHandle,0,2);
      FileSeek(iFileHandle,0,0);
      Buffer := PChar(System.AllocMem(iFileLength + 1));
      iBytesRead := SysUtils.FileRead(iFileHandle, Buffer^, iFileLength);
      FileClose(iFileHandle);
      for i := 0 to iBytesRead-1 do
      begin
        StringGrid1.RowCount := StringGrid1.RowCount + 1;
        StringGrid1.Cells[1,i+1] := Buffer[i];
        StringGrid1.Cells[2,i+1] := IntToStr(Integer(Buffer[i]));
      end;
    finally
      FreeMem(Buffer);
    end;
  end;
end;
{
The following example opens a file of your choice and reads
the entire file into a dynamically allocated buffer. The
buffer and the size of the file are then passed to a routine
that processes the text, and finally the dynamically
allocated buffer is freed and the file is closed.
} 
procedure TForm1.Button1Click(Sender: TObject);
var
  F: file;
  Size: Integer;
  Buffer: PChar;
begin
  if OpenDialog1.Execute then
  begin
    AssignFile(F, OpenDialog1.FileName);
    Reset(F, 1);
    try
      Size := FileSize(F);
      GetMem(Buffer, Size);
      try
        BlockRead(F, Buffer^, Size);
        Memo1.Lines.Add(Buffer);
      finally
        FreeMem(Buffer);
      end;
    finally
      CloseFile(F);
    end;
  end;
end;

 

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