DelphiBasics
FreeMem
Procedure
Free memory storage used by a variable System unit
 procedure FreeMem ( MemoryPointer : Pointer {; MemorySize : Integer} ) ;
Description
The FreeMem procedure frees up memory storage used by a variable MemoryPointer.
 
You can optionally specify the MemorySize to be freed. However, you must specify the size allocated in the first place.
 
If the variable is nil then nothing happens.
 
If the variable invalidly points to memory (maybe it has already been freed), then an EInvalidPointer exception is thrown.
 
If the memory contains references to memory based variables, you must call Finalize before FreeMem.
 
FreeMem is the counter command to GetMem.
 
Ideally, you should use New and Dispose instead of GetMem and FreeMem. It avoids the need to call Finalize.
Related commands
Dispose Dispose of storage used by a pointer type variable
GetMem Get a specified number of storage bytes
New Create a new pointer type variable
ReallocMem Reallocate an existing block of storage
 Author links

 Buy Website Traffic at
 Buywebsitetrafficexperts.com

 Buy Proxies at
 Buyproxies.io
 
 Download this web site as a Windows program.




 
Example code : A simple exampl of using GetMem and FreeMem
// Full Unit code.
// -----------------------------------------------------------
// You must store this code in a unit called Unit1 with a form
// called Form1 that has an OnCreate event called FormCreate.
 
unit Unit1;
 
interface
 
uses
  // The System unit does not need to be defined
  Forms, Dialogs;
 
type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  end;
 
var
  
Form1: TForm1;
 
implementation
{$R *.dfm} // Include form definitions
 
procedure TForm1.FormCreate(Sender: TObject);

var
  charPtr  : PChar;

begin
  // Allocate storage for 4 characters
  GetMem(charPtr, 4 * SizeOf(Char));

  // Assign to these characters
  charPtr^ := 'A';
  Inc(charPtr);
  charPtr^ := 'B';
  Inc(charPtr);
  charPtr^ := 'C';
  Inc(charPtr);
  charPtr^ := #0;  // String terminator

  // Now display these values
  Dec(charPtr, 3);
  ShowMessage('Characters stored = '+charPtr);

  // Now free the memory for these characters
  FreeMem(charPtr);
end;
 
end.
Hide full unit code
   Characters stored = ABC
 
Delphi Programming Neil Moffatt 2002 - 2017. All rights reserved.  |  Home Page