Memory leak with dynamic array
bearophile
bearophileHUGS at lycos.com
Sat Apr 10 11:18:20 PDT 2010
Joseph Wakeling:
> Can anyone advise? :-)
Dynamic arrays in D are not black boxes, they are an abstraction that leaks a lot, so you must know how dynamic arrays are implemented. Recently the implementation of dynamic arrays being changed, has someone a link to a description of how they work now?
Few notes on your code: there is no need to import std.array into that little program. Often there is no need to add an "uint" inside the foreach. I suggest to put a space after every comma. I also suggest you to write big numbers like this: 5_000_000 because they can avoid some mistakes.
>From the little I know about the new arrays this doesn't work anymore, zeroing the length produces a deallocation:
x.length = 5_000_000;
x.length = 0;
So a basic strategy to face your problem is to not let the GC work:
import std.stdio: writefln;
void main() {
auto x = new real[5_000_000];
foreach (i; 0 .. 1_000) {
int x_len = 0;
foreach (j; 0 .. 5_000_000) {
x[x_len] = j;
x_len++;
}
writefln("At iteration %u, x has %u elements.", i, x_len);
}
}
When the GC is not good enough one thing you can do is to manage the memory in a less automatic way...
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list