Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!wasatch!cs.utexas.edu!usc!polyslo!vlsi3b15!lafcol!pilgrimk
From: pilgrimk@lafcol.UUCP (Kenwyn A. Pilgrim)
Newsgroups: comp.lang.pascal
Subject: FreeMem, GetMem & TP50
Message-ID: <1392@lafcol.UUCP>
Date: 16 Aug 89 21:45:44 GMT
Organization: Academic Computer Center, Lafayette College
Lines: 82
Keywords: should order of deallocation matter?


For those of you who have TP50, please try this:

var
 P1,P2: pointer;
begin
 GetMem(P1, 50); {1}
 GetMem(P2, 20); {2}
 FreeMem(P2,20); {3}
 FreeMem(P1,50); {4}
end.

While in the DEBUG mode keep an eye on the MemAvail function
 (Crtl-F7 then MemAvail to put it in watch window);

This is how my TP5 session went

 After Line 1: MemAvail - 50;
 After Line 2: MemAvail - 20;
 After Line 3: MemAvail + 20;
 After Line 4: MemAvail + 50;

So far so good.
Now, switch line {3} with line {4} and run again

The next TP5 session went like this:

 After Line 1: MemAvail - 50;
 After Line 2: MemAvail - 20;
 After New Line 3: MemAvail + 42;
 After New Line 4: MemAvail + 28;

In both cases the available memory was restored to its
value before the program was run, but in the latter case the 
memory is not replaced as expected.

I am in the process of writing a GetMem and FreeMem functions
which would allow me to save memory segments larger than
64K-$F (using a list of pointers). 

I can MyGetMem(P, AnySize) fine, but on occasions MyFreeMem(P)
would say:

           Error 204: Invalid pointer operation 

esp. when the size allocated is close to the MemAvail (plus or minus
100, for instance). All other tests outside of this range
seem fine (and there were many, but that may not prove much).

I would like to think that the problem here is not my logic
but the way in which TP50 handles memory allocation/deallocation :-(

For those of you who are curious the list is like
 ListPtr = ^PtrRec;
 PtrRec = record
           SavePtr: pointer;
           Size   : word; {never more than 64K - $F - SizeOf(PtrRec)}
           Next: ListPtr
          end;

and my routines are 
  procedure MyGetMem(P: pointer; Size: longint);
  procedure MyFreeMem(P: pointer);

(I don't need the size of the memory allocated because
 it's already stored in the variable Size)

And yes! I do take into consideration the memory used for each element of
the actual list (i.e. SizeOf(PtrRec) for each 64K-$F or less stored)

Also, because of the way MyGetMem routine allocates memory,
the MyFreeMem routine deallocates the memory FIFO - so maybe
this is where the problem lies. Maybe if I deallocate it LIFO...

Hmmm. Bye for now with that thought.
Thanks in advance for any helpful hints, thought, pointers, etc.

 -Kenwyn

P.S.
I would expect the same fragmentation problems inherent with the way in
which TP5 manages memory, but nothing like this!