Page 1 of 1
Freeing arrays at procedure exit?
Posted: Fri May 06, 2011 1:21 pm
by MachineCode
Do I need to explicitly call FreeArray() when arrays are used in a procedure, and the procedure exits? The manual doesn't say. The arrays are not global or shared; they're just created with "Dim" at the start of the procedure, and I don't need to preserve their contents when the procedure exits.
Re: Freeing arrays at procedure exit?
Posted: Fri May 06, 2011 1:56 pm
by Trond
It's not needed.
Re: Freeing arrays at procedure exit?
Posted: Fri May 06, 2011 2:30 pm
by MachineCode
Thank you, Trond. Perhaps the manual could be updated in the FreeArray() entry to reflect this fact.
Re: Freeing arrays at procedure exit?
Posted: Fri May 06, 2011 9:33 pm
by shadow
FreeArray() is used du reuse the same array variable name for a new dimensioned array, like ReAllocMemory().
BTW all allocated memory is freed up when the program is closed with End.
If I'm on the wrong way please correct me

Re: Freeing arrays at procedure exit?
Posted: Sat May 07, 2011 2:40 pm
by Zefz
A related question. Take a look at this code:
Code: Select all
Structure MyStruct
*MemoryAddress
VarA.w
VarB.w
EndStructure
Global Dim MyArray.MyStruct(10)
For i = 0 To 10
MyArray(i)\MemoryAddress = AllocateMemory(2048)
Next
FreeArray( MyArray() )
Is there a memory leak now because I did not FreeMemory() on each *MemoryAddress in the array? Or does FreeArray automatically handle this for us?
Re: Freeing arrays at procedure exit?
Posted: Sat May 07, 2011 3:17 pm
by Demivec
Zefz wrote:A related question. Take a look at this code:
Code: Select all
Structure MyStruct
*MemoryAddress
VarA.w
VarB.w
EndStructure
Global Dim MyArray.MyStruct(10)
For i = 0 To 10
MyArray(i)\MemoryAddress = AllocateMemory(2048)
Next
FreeArray( MyArray() )
Is there a memory leak now because I did not FreeMemory() on each *MemoryAddress in the array? Or does FreeArray automatically handle this for us?
Yes there would be a memory leak. A pointer is not an object. If your example was written a little differently all the pointers in the array could be pointing to the same object or to objects that will persist even after the array's memory is freed.
FreeArray() does not handle memory that is allocated in addition to the space needed for the storage of an array's elements (strings being a notable exception) and the array's bookkeeping (i.e. dimensions, and element size). This means that it will free the memory needed to store the pointer, not the memory it may point to.
I thought there was a mention of this in the manual but I wasn't able to locate a quote to confirm this.