[fpc-pascal] Code conversion question - alloc and dealloc memory

Graeme Geldenhuys graemeg.lists at gmail.com
Thu Oct 15 10:15:06 CEST 2009


Hi,

I'm am having problems allocating memory and then populating that
memory with a TFileStream.Read() call. So I thought, maybe my GetMem()
call is incorrect. I then looked at the original code I am porting
from, which had these methods instead. If I get this memory allocation
correct, I'll see if it is needed to ask a question abotu the
TFileStream.Read() issue I have.

Do I need these methods, or does the standard GetMem() & FreeMem() in
FPC handle all this for me. What if I don't pass in a size to
FreeMem(), will it know how much to free?

Please note that this code DOES NOT compile on my 64bit system, as
there is no "pLong" type defined.  I tried replacing pLong with PtrInt
& longint with Integer (for 64bit support), but then the compiler
complains and says the dereference statements are invalid.

Looking at the code I understand this as follows - please correct me
if I am wrong. When it allocates memory, it actually allocates the
size as Size + sizeof(Size) bigger and then uses the first area in
memory to store the "size" allocated, so that it can be retrieved
later when deallocating the memmory and can find out exactly by how
much it must deallocate.

------------------------
function AllocateMemory( const Size: longint ): pointer;
begin
  GetMem( Result, size + sizeof( Size ) );
  pLong( Result )^ := Size;
  inc( Result, sizeof( Size ) );
end;

procedure DeallocateMemory( Var P: pointer );
var
  Size: longint;
begin
  if P = nil then
    exit;

  dec( P, sizeof( Size ) );
  Size := pLong( P )^;
  FreeMem( P, Size + sizeof( Size ) );
  P := nil;
end;

------------------------



-- 
Regards,
  - Graeme -


_______________________________________________
fpGUI - a cross-platform Free Pascal GUI toolkit
http://opensoft.homeip.net/fpgui/



More information about the fpc-pascal mailing list