Delphi Basics
ReallocMem
Procedure
Reallocate an existing block of storage System unit
 procedure ReallocMem ( var StoragePointer : Pointer; StorageSize : Integer ) ;
Description
The ReallocMem procedure changes the storage size of an existing block of storage.
 
The size may be smaller or bigger.
 
If smaller, then the existing storage is effectively truncated, the remainder being released.
 
If larger, the storage is extended. Or a new block is allocated if necessary. In either case, the existing storage block data is preserved, and the new part is unitialised.
Notes
Warning : use with caution - excessive use can fragment storage.
Related commands
Dispose Dispose of storage used by a pointer type variable
FreeMem Free memory storage used by a variable
GetMem Get a specified number of storage bytes
New Create a new pointer type variable
 
Example code : Allocate using GetMem and then reallocate using ReallocMem
// 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);

type
  TRecord = Record
    name : string[10];
    age  : Byte;
  end;

var
  recPointer : ^TRecord;

begin
  // Allocate storage for 2 records
  // Note : It is better to use New for this
  // It is used here for illustration purposes only
  GetMem(recPointer, 2 * SizeOf(TRecord));

  // Fill out these 2 records with values
  recPointer.name := 'Brian';
  recPointer.age  := 23;

  Inc(recPointer);
  recPointer.name := 'Jim';
  recPointer.age  := 55;

  // Whoops - forgot to add Sally ...
  Dec(recPointer);
  ReallocMem(recPointer, 3 * SizeOf(TRecord));

  // Now add a third record
  Inc(recPointer,2);
  recPointer.name := 'Sally';
  recPointer.age  := 38;

  // Now display these values
  Dec(recPointer, 2);
  ShowMessageFmt('%s is %d',[recPointer.name, recPointer.age]);
  Inc(recPointer);
  ShowMessageFmt('%s is %d',[recPointer.name, recPointer.age]);
  Inc(recPointer);
  ShowMessageFmt('%s is %d',[recPointer.name, recPointer.age]);
end;
 
end.
Hide full unit code
   Brian is 23
   Jim is 55
   Sally is 38
 
 
© CodeGear 2006 - 2007. All rights reserved.  |  Home Page