Memory leak in foreach

Andrea Fontana nospam at example.org
Wed Feb 20 12:31:43 UTC 2019


On Wednesday, 20 February 2019 at 11:05:31 UTC, Dein wrote:
> On Wednesday, 20 February 2019 at 09:31:30 UTC, Andrea Fontana 
> wrote:
>> This subtle bug[1] and its memory leak are still here because 
>> my pull request[2] had no success.
>>
>> It worths noting that since each() in std.algorithm uses a 
>> foreach+ref to iterate  structs[3], this memory leak probably 
>> is silently affecting not only me :)
>>
>> I hope someone could fix this.
>>
>> [1] https://issues.dlang.org/show_bug.cgi?id=11934
>> [2] https://github.com/dlang/dmd/pull/8437
>> [3] 
>> https://github.com/dlang/phobos/blob/master/std/algorithm/iteration.d#L983
>
> That's not a memory leak, you are creating a GC array, the GC 
> might never free the array its not deterministic. Use @nogc and 
> staticArray() if you want to destructors to be called 
> deterministically.


If you check the example you will notice that for each element 
inside the array is created a copy by foreach. Those temporary 
copies are never freed (bug). So each time you are going to 
iterate through your array (using ref) you are filling  memory 
with additional copies of your elements.



More information about the Digitalmars-d mailing list