* Re: Very basic questions about memory allocation
1999-07-30 0:00 Very basic questions about memory allocation JIMHER@yanoesladirecci�n.com
@ 1999-07-30 0:00 ` Frank Ecke
1999-08-01 0:00 ` JIMHER@yanoesladirecci�n.com
1999-07-31 0:00 ` tmoran
1 sibling, 1 reply; 4+ messages in thread
From: Frank Ecke @ 1999-07-30 0:00 UTC (permalink / raw)
Upon Fri, 30 Jul 1999 22:46:56 +0200, JIMHER@yanoesladirecci�n.com
<vtis0102@CACANOps.uib.es> spake unto us thuswise:
> I'm starting to work in ADA
I'm pleased to hear that.
> but i've found some problems. The principal
> one is that I son't know how to free memory previously allocated with:
>
> type t is ....
> ...
> v:access t;
> begin
> v:=new t;
> end;
>
>
> I've tried 'free(v)', 'delete v' and others, but they don't work. I use
> to program in C, and I only want an equivalent to 'free(v)'.
Actually, it is all there, but it's a bit, well, hidden. Ada is a
strongly typed language. Therefore, access types are not just
pointers, but each access type has associated with it the type it
points to. Each time you create a new access type, it is different
from all the previously created access types in your program (this
sentence could be rewritten without using the word ``access''). As
a consequence, there cannot be a single procedure to deallocate all
objects---each object is of a particular type: you need a
deallocation procedure for each access type in your program. You
cannot use a Free-procedure intended for strings to deallocate
integer objects. On the other hand, it would be impossible for the
Ada language to ``have on stock'' all the Free-procedures necessary
in your program. The solution to this dilemma is given by generics.
Ada provides one generic procedure, called Unchecked_Deallocation,
which you are supposed to instantiate with an actual access type.
See ARM (Ada Reference Manual) 13.11.2.
Thus, returning to your example code from above, the following
solves the problem:
-- T and U are different
type T is ...;
type U is ...;
type T_Ptr is access T;
type U_Ptr is access U;
-- instantiate two deallocation procedures; one for T and one for U
procedure Free is new Ada.Unchecked_Deallocation(T, T_Ptr);
procedure Delete is new Ada.Unchecked_Deallocation(U, U_Ptr);
Foo : T_Ptr;
Bar : U_Ptr;
begin
--- create them
Foo := new T;
Bar := new U;
-- use them
...
-- kill them
Free(Foo);
Delete(Bar);
end;
Note that you can create the *illusion* of one general
deallocation procedure: you could replace ``Delete'' by ``Free'' (but
be sure to replace *all* occurrences of ``Delete'' by ``Free'').
Mind you, it is an illusion; there are still two different
Free-procedures. The secret behind this is the concept of
overloading, which is revealed in ARM 8.6.
I hope this helps,
Frank
--
Frank Ecke <franke@minet.uni-jena.de>
In a world without walls and fences, who needeth windows and gates?
^ permalink raw reply [flat|nested] 4+ messages in thread