[fpc-pascal] How to free this memory and avoid memory leak

Jonas Maebe jonas.maebe at elis.ugent.be
Thu Oct 8 15:56:37 CEST 2009


On 08 Oct 2009, at 15:51, Graeme Geldenhuys wrote:

> procedure THelpFile.ReadContents;
> var
>  Topic: TTopic;
>  EntryIndex: longint;
>  pEntry: pTTOCEntryStart;
>  tocarray: array of Int32;
>  p: PByte;
> begin
>  _Topics.Capacity := _Header.ntoc;
>
>  SetLength(tocarray, _Header.ntoc);
>  p := _Data + _Header.tocoffsetsstart;
>  Move(p, tocarray, SizeOf(tocarray));

This has to be

move(p^, tocarray^, length(tocarray)*sizeof(tocarray[0]));

Otherwise you are just moving the contents of "p" into tocarray, and  
the pointer to the memory allocated for tocarray is gone forever.  
You're lucky (or unlucky) the program didn't crash when finalising  
tocarray.

Also, as you can see the program does not really depend on the data  
being actually stored in a dynamic array. So you could just as well  
use "tocarray: ^Int32" and assign it the value of p (as you pretty  
much did until now).


Jonas



More information about the fpc-pascal mailing list