• 🏆 Texturing Contest #33 is OPEN! Contestants must re-texture a SD unit model found in-game (Warcraft 3 Classic), recreating the unit into a peaceful NPC version. 🔗Click here to enter!
  • It's time for the first HD Modeling Contest of 2024. Join the theme discussion for Hive's HD Modeling Contest #6! Click here to post your idea!

Question: unit and location variable leaks

Status
Not open for further replies.
Level 1
Joined
Nov 9, 2019
Messages
1
Question about unit and location variable leaks when they are in a loop...see partial code below:

JASS:
function example takes nothing returns nothing

local group g = CreateGroup()
local unit u
local location l

//code here to add units to group, omitted for clarity

loop
    set u = FirstOfGroup(g)
    exitwhen u == null
    set l = //some location, different each time the loop runs

    //code to have unit do something with location

    call GroupRemoveUnit(g, u)
    //Do I need to null the unit and/or location variable here to prevent from leaking on the next iteration of the loop?
    //Or is it only necessary to do that at the end of the function?
endloop

call GroupClear(g)
call DestroyGroup(g)
set g = null

call RemoveLocation(l)
set u = null

endfunction

Where should the unit variable and location variable be nulled to prevent this function from leaking? Within the loop or at end of function?
 
Level 39
Joined
Feb 27, 2007
Messages
5,008
You need to destroy the locations when they are no longer needed. So that would be inside the loop. If you do not destroy them the variable l will be overwritten and you’ll lose reference to the location, permanently leaking the data.

Nulling local variables needs to happen at the end of a function (before a return statement). If you do not null them the handle id used for that handle stays in use permanently. The local variable can only be accessed/modified in the function it was declared, so it leaks the reference if not nulled. Globals do not need to be nulled.

In this instance l needs to be nulled but u does not because, by the loop exitwhen logic, u is already null at the end of the function.
 

Dr Super Good

Spell Reviewer
Level 63
Joined
Jan 18, 2005
Messages
27,195
Where should the unit variable and location variable be nulled to prevent this function from leaking? Within the loop or at end of function?
Just before the function returns. If the only return is at the end of the function then there. If there are explicit function returns in the middle then just before those are executed. This only applies to JASS, since Lua does not suffer from this.
 
Status
Not open for further replies.
Top