Fix memory leak caused by mutating an array while iterating over it.