delphi - Correctly allocating/freeing memory for records in static array -
yesterday had memory corruption going on , i'm highly suspect of how record arrays being allocated , deallocated. short version demostration:
type tmyrecord = record w: word; s: string; end; tmyrecordarray = array [1 .. 315] of tmyrecord; tarraypointer = ^tmyrecordarray; var pagebase: tarraypointer; procedure ttestform.formcreate(sender: tobject); var irecord: tmyrecord; begin pagebase := allocmem(sizeof(tmyrecordarray)); irecord.w := 1; irecord.s := 'test'; pagebase^[1] := irecord; end; procedure ttestform.formdestroy(sender: tobject); begin pagebase^[1] := default (tmyrecord); freemem(tpagebase); end;
i'm sure i'm not doing right, suggestions appreciated.
the first thing code present works. finalizes , deallocate correctly without leaking. i'll try answer question more generally.
strings managed types , compiler needs use special memory allocation routines able manage them: new
, dispose
.
allocate with
new(pagebase);
and deallocate with:
dispose(pagebase);
the call new
ensures members managed default initialized. , in other direction, dispose
finalize managed members.
you manually code attempts. in real code need finalize every element of array. code finalizes one. of course, initializes 1 , written in question fine. perhaps short version question has simplified far fault has been removed.
however, not recommending deal managed types manually. use new
, dispose
that.
it's worth saying dynamic array simpler here. using dynamic array let compiler take care of allocation , deallocation, , handle managed types correctly.
Comments
Post a Comment