Jump to content
PeaShooter_OMO

Casting an untyped pointer to a typed when using with New() and Dispose()

Recommended Posts

Posted (edited)
type
  TMyRec = record
    Int : Integer;
    Str : String;
  end;
  PMyRec = ^TMyRec;
var
  LPointer : Pointer;
begin
  New(PMyRec(LPointer));
  PMyRec(LPointer)^.Int := 200;
  PMyRec(LPointer)^.Str := 'Blah';
  Dispose(PMyRec(LPointer));
end;

I do not know why this approach bothers me but for some reason it does. I am casting a Pointer to a PMyRec to use it with New() and Dispose().

 

I do not get a memory leak from this so I am assuming it will be operating correctly. Am I right?

 

Edit:

I understand that typed pointers are to be used with New() and Dispose(). This is just an experiment into the working of the memory around this and also New() and Dispose(). That's all.

Edited by PeaShooter_OMO

Share this post


Link to post

If you must use NEW (so create a new variable), why don't declare it like a normal variable or a typed pointer? If you refer a record variable you don't need to allocate memory.

 

If you need to reference a pointer, this normally means that it's already assigned and you can cast without NEW or DISPOSE.

 

Another suggestion: in Delphi you don't need to "defererence" a typed pointer, the compiler do it for you:

 

var
  LPointer : Pointer;
begin
  New(PMyRec(LPointer));
  PMyRec(LPointer).Int := 200;
  PMyRec(LPointer).Str := 'Blah';
  Dispose(PMyRec(LPointer));
end;

var
  LPointer : PMyRec;
begin
  New(LPointer);
  LPointer.Int := 200;
  LPointer.Str := 'Blah';
  Dispose(LPointer);
end;

 

Share this post


Link to post
3 hours ago, PeaShooter_OMO said:

type
  TMyRec = record
    Int : Integer;
    Str : String;
  end;
  PMyRec = ^TMyRec;

var
  LPointer : Pointer;
begin
  New(PMyRec(LPointer));
  PMyRec(LPointer)^.Int := 200;
  PMyRec(LPointer)^.Str := 'Blah';
  Dispose(PMyRec(LPointer));
end;

I do not know why this approach bothers me but for some reason it does. I am casting a Pointer to a PMyRec to use it with New() and Dispose().

 

I do not get a memory leak from this so I am assuming it will be operating correctly. Am I right?

 

 

 

It will work but there is no point in doing it this way. Declare LPointer as type PMyRec and work with that. Don't use C idioms with Delphi, that only confuses things.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×