[fpc-pascal] why dynamic array created in constructor not automatically free in destructor

J├╝rgen Hestermann juergen.hestermann at gmx.de
Thu Aug 7 11:25:16 CEST 2014


Am 2014-08-07 10:21, schrieb Dennis Poon:
 > TMyClass=class
 > public
 >   ar : array of integer;
 >   constructor Create;
 >  destructor destroy;override;
 > end;
 > TMyClass.Create;
 > begin
 >    inherited;
 >    SetLength(ar, 100);
 > end;
 > TMyClass.Destroy;
 > begin
 >    ar := nil;//<--- this is needed otherwise a memory leak is reported!
 >   inherited;
 > end;
 > I would expect the compiler would automatically insert this ar := nil on my behalf because it seems like it does it for strings.
 > Am I missing some compiler directives?


I think strings are a very special case because they are treated diffently in many cases.
Strings can be freed without harm because they are well defined and no parts of them
point to other objects on the heap. They have a reference counter where the compiler
logs how many instances are pointing to the string and only removes it when it has
reached zero.

If you have a dynamic array then elements may point to other structures (which again
may point to a structure that....) which again need to be freed.
If you have allocated memory yourself then the compiler does not know
how (and when) to free these objects. They may be used in other arrays or elsewhere.





More information about the fpc-pascal mailing list