Re: SetSize...
- From: Rob Kennedy <me3@xxxxxxxxxxx>
- Date: Thu, 01 Jun 2006 10:03:29 -0500
alanglloyd@xxxxxxx wrote:
Rob Kennedy wrote:Ove wrote:<snip><snip>type PDataRec = ^ADataRec;
ADataRec = record
p := New(PDataRec);
Usually, that's just written "New(p);" not as an assignment statement.
But better written ..
var
PtrDataRec : PDataRec;
PtrDataRec := AllocMem(SizeOf(TDataRec);
I disagree. For one thing, you now have to make sure you get the size correct, whereas with New, the compiler figures out the size based on the type of the variable you're using.
... then not only is the memory zero-ed (each byte set to 0)
Which is only correct if the default initializations of all the record's fields is all-bits-zero, and that is not necessarily the case. The New procedure will initialize all the fields that need initialization as though the Initialize procedure had been called.
but the
pointer is properly typed (instead of being a generic pointer)
The p variable in Ove's and my code was not a generic pointer. If it were, my call to New would not have compiled.
and thus
it is brought within Delphi's strict type-checking, which protects you
from a lot of errors and results in a better standard of coding.
Not really. AllocMem returns type Pointer. You can assign that to any pointer-typed variable. (I think you can even assign it to an object reference or interface reference!) There's no checking to ensure that the value you get is assigned to a PDataRec value just because you called AllocMem with SizeOf(TDataRec).
Of course don't forget to ...
FreeMem(PtrDataRec) when you have finished with the record.
And that' the worst part. When you do that, you leak the dynamic array in the record. FreeMem doesn't know anything about the type of the variable you give to it. All it knows is the size of the memory block. The Dispose procedure, on the other hand, will behave as though Finalize were called on the variable before freeing the memory.
New = GetMem + Initialize
Dispose = Finalize + FreeMem
--
Rob
.
- References:
- SetSize...
- From: Ove
- Re: SetSize...
- From: Rob Kennedy
- Re: SetSize...
- From: alanglloyd
- SetSize...
- Prev by Date: Having package name displayed?
- Next by Date: Re: Having package name displayed?
- Previous by thread: Re: SetSize...
- Next by thread: Re: SetSize...
- Index(es):
Relevant Pages
|