Arrays

Stewart Gordon smjg_1998 at yahoo.com
Wed Jan 10 19:42:53 PST 2007


Olli Aalto wrote:
> Hi!
> 
> I've been playing with arrays lately. Static arrays, 2/3/4 dimensional 
> arrays and dynamic arrays.
> 
> First I'd like to ask if it's safe to do this:
> 
> int[] getIntArrayWithLengthOf2()
> {
>     int[] array = new int[2];
>     array[] = 2;
>     return array;
> }
> 
> some scope
> {
>     int[2] array2 = getIntArrayWithLengthOf2();
> }
> 
> It seem to work, but what about memory? How's it handled? Do I need to 
> delete it if I don't want the GC take care of it?
<snip>

You have declared an int[2], that is a static array, so it is allocated 
on the stack.  What happens is that getIntArrayWithLengthOf2 allocates 
an array on the heap, and then its contents are copied into array2.  The 
array allocated on the heap becomes unreachable, and so will be picked 
up by the GC the next time it runs, even if control is still within some 
scope.  The copy in array2, OTOH, will persist until the end of the scope.

If OTOH you declared

     int[] array2 = getIntArrayWithLengthOf2();

then array2 is a dynamic array.  Assignment is then by reference, and so 
array2 points into the memory allocated on the heap by 
getIntArrayWithLengthOf2.  The GC will not free the heap-allocated 
memory until array2 goes out of scope or is assigned something else. 
Even then, it will only free it if no other reachable reference to it 
exists.

Stewart.


More information about the Digitalmars-d-learn mailing list