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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With