Memory leak with dynamic array

bearophile bearophileHUGS at lycos.com
Sat Apr 10 13:11:47 PDT 2010


Joseph Wakeling:

> Can anyone advise? :-)

My precedent answer was ignorant. Read about the capacity, reserve and assumeSafeAppend here:
http://www.digitalmars.com/d/2.0/phobos/object.html

I think a short page about the design of the new dynamic arrays can be added to the D site.

This is a version of the program that doesn't blow up the memory (it uses more and more memory but just a bit):

import std.stdio: writeln, writefln;

void main() {
    enum int N = 5_000_000;
    real[] arr;
    writeln("A) arr.capacity: ", arr.capacity);
    arr.reserve(N); // optional
    writeln("B) arr.capacity: ", arr.capacity);

    foreach (i; 0 .. 100) {
        arr.length = 0;
        writeln("1) arr.capacity: ", arr.capacity);
        assumeSafeAppend(arr); // not optional
        writeln("2) arr.capacity: ", arr.capacity);

        foreach (j; 0 .. N)
            arr ~= j;

        writefln("At iteration %u, arr has %u elements.", i, arr.length);
    }
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list