Handling Out Of Memory

From: Skybuck Flying (nospam_at_hotmail.com)
Date: 03/31/04


Date: Wed, 31 Mar 2004 10:43:33 +0200

I find a GetMem function more intuitive then a GetMem procedure which would
raise an exception if it failed.

// reallocate example with getmem function

 if GetMem( NewBuffer, NewSize ) then
 begin

  // maximize copy
  CopySize := NewSize;

  / if old buffer is smaller than minimize copy
  if Size < NewSize then
  begin
   CopySize := Size; // old size
  end;

  // copy buffer to new buffer
  move( Buffer^, NewBuffer^, CopySize );

  // free old buffer
  FreeMem( Buffer, Size );

  // set new size
  Size := NewSize;

  // set new buffer
  Buffer := NewBuffer;

 end else
 begin
  // allocation failed, keep old buffer

  // or if you want free old buffer lol :D

 end;

// reallocate example with getmem procedure with crazy exception :D

 try
  GetMem( NewBuffer, NewSize );

  // maximize copy
  CopySize := NewSize;

  / if old buffer is smaller than minimize copy
  if Size < NewSize then
  begin
   CopySize := Size; // old size
  end;

  // copy buffer to new buffer
  move( Buffer^, NewBuffer^, CopySize );

  // free old buffer
  FreeMem( Buffer, Size );

  // set new size
  Size := NewSize;

  // set new buffer
  Buffer := NewBuffer;

 except
  // allocation failed, keep old buffer

  // or if you want free old buffer lol :D

 end;

 It's exactly the same code... but developing the first code was easy
 it was clear to see how to do it... the second example was though
 if you had to do it from scratch.. it would be less intuitive.
 The second example was derived from the first one.

Fortunately a GetMem function I can created for easy of use :D

function GetMem( var P : pointer; Size : integer ) : boolean;
begin
 result := false;

 try
  // GetMem( P, Size ); // recursion !
  System.GetMem( P, Size ); // prevent recursion :D

  result := true;
 except

 end;

end;

Skybuck :D



Relevant Pages

  • Re: Buffer growing strategy?
    ... I'm looking into a buffer ... growing strategy to double the memory (or more generally multiply with a ... newsize = oldsize * FACTOR; ... But with powers of two the size will grow as 16, 32, 64 and there is always some space that can't be used. ...
    (comp.lang.c)
  • Re: Buffer growing strategy?
    ... I'm looking into a buffer ... newsize = oldsize * FACTOR; ... A very simple solution is to just call realloc for the new size ...
    (comp.lang.c)
  • Buffer growing strategy?
    ... I'm looking into a buffer growing strategy to double the memory. ... newsize = oldsize * FACTOR; ... (I'm aware that I have to take extra care in case oldsize is zero, or with multiplications with a non-integer FACTOR.) ... Or is that just a matter of personal preference? ...
    (comp.lang.c)