leuage
leuage

Reputation: 566

A freed access type variable is supposed to be set to NULL; why does it keep the same address?

According to the Adacore website, once an access type variable is freed then it is set to null. Then why does the same address get printed before and after Free?

with ada.Text_IO,ada.Integer_Text_IO;
with ada.Unchecked_Deallocation;
with System.Address_Image;
procedure hello is
   type my_access is access all integer;
   procedure free is new ada.Unchecked_Deallocation(integer,my_access);
   var:my_access:=new integer;
begin
   ada.Text_IO.put_line(System.Address_Image(var'Address));   --- same address
   var.all:=90;
   ada.Integer_Text_IO.put(var.all);
   free(var); -- after free it is set to Null then why same address?
   ada.Text_IO.put_line(System.Address_Image(var'Address));  --- same address why?
end hello;

Upvotes: 0

Views: 90

Answers (1)

ajb
ajb

Reputation: 31699

var is an access variable that points to (or accesses) an integer. The access variable var typically lives on the stack. It typically uses 4 or 8 bytes of memory. When hello is called, the program allocates an integer on the "heap", and sets var to point to the integer. Therefore, var will contain the address of the new integer (the Ada language doesn't require that it actually contains the address, but in most implementations it will). After you free it, var will contain null.

However, var'address doesn't give you the address of the integer, or the contents of the 4 or 8 byte pointer. var'address is the address of the pointer itself--that is, the address of the 4 or 8 bytes it uses on the stack.

If you want to get the address of the integer, var.all'address will work unless var is null, and then an exception will be raised. Another way to convert between an access value and an address is System.Address_To_Access_Conversions. That works with the address of the integer that got allocated on the heap, not with the address of the access variable on the stack.

Upvotes: 4

Related Questions