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

Jonas Maebe jonas.maebe at elis.ugent.be
Thu Oct 8 16:30:44 CEST 2009


On 08 Oct 2009, at 16:18, Graeme Geldenhuys wrote:

> 2009/10/8 Jonas Maebe <jonas.maebe at elis.ugent.be>:
>>>  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]));
>                                 ^
> This gives a compiler error. Illegal qualifier and points to the
> second ^ in that statement.

It should have read move(p^, tocarray[0],  
length(tocarray)*sizeof(tocarray[0]));

>    move(p^, tocarray, _Header.ntoc*sizeof(tocarray[0]));
> Causes a segmentation fault at runtime.

That's is because you are blasting "_Header.ntoc*sizeof(tocarray[0])"  
bytes of data onto the stack starting at the address of tocarray.  
sizeof(tocarray) = sizeof(pointer). You are therefore overwriting  
everything on the stack coming after that variable (= higher on the  
stack).

>      Move(p, tocarray[0], SizeOf(tocarray));
> This causes an Access Violation at runtime.

That's because you are only initialising the first element (with the  
*value* of p no less, which is not a valid index in your file, but a  
pointer to some memory location), and later on reading every other  
element and using it as index in your loop.

> My problem is not reading in the data. It reads in perfectly,

I explained in my original mail what that is the case (which you  
apparently saw in the mean time).

> it's
> just the cleanup of the local array that I am battling with.

Also with understanding how dynamic arrays and/or move work. Dynamic  
arrays are reference counted pointers to data blobs.  
sizeof(dynamic_array_var) = sizeof(pointer), always, and regardless of  
the length of the array. It's like sizeof(class) = sizeof(ansistring)  
= sizeof(pointer). Move() takes "var" parameters as first and second  
parameters, which means that it will read data from the memory  
*occupied by* the first argument (rather than memory it may point at)  
and store data into the memory *occupied by* the second argument (idem).

> Heaptrc
> keeps telling me there is a memory leak.

It is correct.


Jonas



More information about the fpc-pascal mailing list