GetMem Procedure
GetMem
allocates Size
bytes of
dynamic memory and stores a pointer to the memory in
P
. It does not initialize the allocated memory.
GetMem
is not a real procedure.
The memory that GetMem
allocates is not
initialized. If you are allocating strings, dynamic arrays, or
Variant
s, you should call
Initialize
or set the memory to zero with
FillChar
.
GetMem
in Delphi’s default memory manager is
thread-safe, that is, you can call GetMem
from
multiple threads simultaneously, but only if
IsMultiThread
is True.
If you are allocating a record or fixed-size array, call
New
instead of
GetMem
.
A common use for GetMem
is to allocate an array
where you do not know the array size at compile time. Although
dynamic arrays have largely replaced the need for this trick, it is
still commonly found in legacy Delphi
code.
// Create a grayscale palette, and return the palette handle. // Although you can create a palette with up to 255 shades of gray, // many video adapters can display only 15 or 16 bits per pixel, // which means 5 bits per gray shade, or 32 distinct shades of gray. function CreateGrayScalePalette(NumShades: Bytes); var LogPalette: PLogPalette; I: Integer; begin // TLogPalette already has room for one palette entry, so allocate // room for NumShades-1 additional palette entries. GetMem(LogPalette, SizeOf(TLogPalette) + (NumShades-1)*SizeOf(TPaletteEntry)); try LogPalette.palVersion := $300; LogPalette.palNumEntries := NumShades; // TLogPalette defines the palPalEntry array with bounds 0..0 // so turn off range checking to set the other array entries. {$R-} for I := 0 to NumShades-1 do begin LogPalette.palPalEntry[I].peRed := I * 256 div NumShades; LogPalette.palPalEntry[I].peGreen := I * 256 div NumShades; LogPalette.palPalEntry[I].peBlue := I * 256 div NumShades; LogPalette.palPalEntry[I].peFlags := 0; end; {$R+} Result := CreatePalette(LogPalette); finally FreeMem(LogPalette) end; end;