qed
qed

Reputation: 23104

Is there a memory leak in this D example?

From the offical D book:

import std.stdio;

void main()
{
    double[] slice1 = [ 1, 1, 1 ];
    double[] slice2 = [ 2, 2, 2 ];
    double[] slice3 = [ 3, 3, 3 ];

    slice2 = slice1;      // ← slice2 starts providing access
                          //   to the same elements that
                          //   slice1 provides access to

    slice3[] = slice1;    // ← the values of the elements of
                          //   slice3 change

    writeln("slice1 before: ", slice1);
    writeln("slice2 before: ", slice2);
    writeln("slice3 before: ", slice3);

    slice2[0] = 42;       // ← the value of an element that
                          //   it shares with slice1 changes

    slice3[0] = 43;       // ← the value of an element that
                          //   only it provides access to
                          //   changes

    writeln("slice1 after : ", slice1);
    writeln("slice2 after : ", slice2);
    writeln("slice3 after : ", slice3);
}

slice2 is pointing to some data, then changed to point to something else, isn't this going to cause a memory leak?

Upvotes: 2

Views: 97

Answers (1)

Vladimir Panteleev
Vladimir Panteleev

Reputation: 25187

D is a garbage collected language. The garbage collector will likely eventually free memory allocated for unreachable objects.

Upvotes: 8

Related Questions