Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

It's ok to allocate a pointer of one type and dispose it as a different type but of the same size?

It's ok to allocate a pointer of one type and dispose it as a different type but of the same size ? I mean like this :

procedure TForm1.Button1Click(Sender: TObject);
var A:PInt64;   // 64bit
    P:Pointer;
    B:PDouble;  // 64bit
begin
  New(A);
  P:=A;
  B:=P;
  Dispose(B);
end;

Let's say I want this only for 8, 16, 32, 64bit signed and unsigned types. It's ok ?

like image 944
Marus Gradinaru Avatar asked Jul 15 '15 20:07

Marus Gradinaru


1 Answers

If the type being pointed at is not a managed type then this is safe. In your case, neither Int64 nor Double are managed types and so this is safe.

An example of a managed type would be a String, interface, Variant, anonymous procedure/method, a record containing managed types, etc.

When you use New and Dispose on a managed type, the object must be initialized and finalized. When you use New and Dispose on an unmanaged type, it is equivalent to calling GetMem and FreeMem.

In fact, you don't need the types being pointed at to be the same size. When the call to FreeMem is made, the size of the type is not passed. The memory being pointed at has metadata for each block that allows it to deallocate the entire block.

like image 112
David Heffernan Avatar answered Nov 02 '22 07:11

David Heffernan