Protected NewList

Just starting out? Need help? Post your questions and find answers here.
sst
New User
New User
Posts: 5
Joined: Fri Jun 21, 2024 9:56 am

Protected NewList

Post by sst »

There are cases where a variable of type List is used only within a procedure (and declared as Protected).

In order to avoid “memory leak”, is it necessary to use the FreeList() command before procedure exit?
The same question in the case of a variable of type Map or Array.
A simple example:

Code: Select all

Procedure   foo()
Protected NewList a.i ()


;Do something with a()


FreeList (a()) ; Is this instruction necessary to avoid memory leak or it is useless?

ProcedureReturn

EndProcedure
BarryG
Addict
Addict
Posts: 4173
Joined: Thu Apr 18, 2019 8:17 am

Re: Protected NewList

Post by BarryG »

I only tested Lists and Arrays, and yes, they're freed when the procedure exits. Proof is below. Run each test and look at the mem usage in Task Manager. Then press the P key to exit the procedure, and the mem usage in Task Manager goes down. Then press E to exit the app.

@Fred: This info would be useful in the manual under "Procedure"?

Arrays:

Code: Select all

Procedure test()
  Dim a$(99999999)
  Repeat : Sleep_(1) : Until GetAsyncKeyState_(#VK_P)<>0 ; Press P to exit this procedure.
EndProcedure

test()

Repeat : Sleep_(1) : Until GetAsyncKeyState_(#VK_E)<>0 ; Press E to exit app.
Lists:

Code: Select all

Procedure test()
  Protected NewList a.i()
  For n=1 To 9999999
    AddElement(a())
    a()=n
  Next
  Repeat : Sleep_(1) : Until GetAsyncKeyState_(#VK_P)<>0 ; Press P to exit this procedure.
EndProcedure

test()

Repeat : Sleep_(1) : Until GetAsyncKeyState_(#VK_E)<>0 ; Press E to exit app.
User avatar
jacdelad
Addict
Addict
Posts: 2009
Joined: Wed Feb 03, 2021 12:46 pm
Location: Riesa

Re: Protected NewList

Post by jacdelad »

They are freed automatically, like BarryG said. One thing to consider is that it may take a while to free them if they are very huge. I had the problem, that a procedure took a long time stopping at returning to the main program. I found out, that releasing the very huge list was the culprit. Solved it with a global list and asynchronous cleanup.
Good morning, that's a nice tnetennba!

PureBasic 6.21/Windows 11 x64/Ryzen 7900X/32GB RAM/3TB SSD
Synology DS1821+/DX517, 130.9TB+50.8TB+2TB SSD
PBJim
Enthusiast
Enthusiast
Posts: 296
Joined: Fri Jan 19, 2024 11:56 pm

Re: Protected NewList

Post by PBJim »

BarryG wrote: Mon Jul 01, 2024 11:27 am @Fred: This info would be useful in the manual under "Procedure"?
It would indeed be good to see this type of broad technical information within PureBasic's documentation. It's precisely the sort of thing that developers more or less know the answer to already, but having it confirmed in the documentation would be so much better.
Post Reply