Resizing an array: Dangerous? Possibly buggy?

%u wfunction at hotmail.com
Wed Mar 9 03:41:54 PST 2011


Increasing the sizes of an array has always given me the shivers, as
beautiful as it is.

Could someone explain why this code behaves the way it does?

    string s = "1234";
    s.length = 7;
    writefln("\"%s\"", s);

prints:  "1234   "

Given that it makes no sense to extend a const-size array, shouldn't
there be a run-time check on the new size of the array, so that it
throws whenever it's bigger than the current size?



Also, another issue:

Let's say you have an array that you dynamically resize (meaning you
grow and shrink it a lot of times). In fact, let's say you have:
    int[] arr = new int[1024 * 1024];
and then you decide, hey, that's too big for how much space I
actually needed:
    arr.length = 5;

Can the rest of the array be garbage collected?

    a. If the answer is "yes", then how does the GC know?
    b. If the answer is "no", then doesn't that:
       (1) Mean that we can have memory leaks?
       (2) Mean that we still need an ArrayList!(T) type?

(Note that using Array!(T) does _NOT_ help here, because it can't
hold object references due to garbage collection issues.)


More information about the Digitalmars-d mailing list