Arrays

Stewart Gordon smjg_1998 at yahoo.com
Wed Jan 10 19:33:48 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?

What do you mean by "don't want the GC take care of it"?

GC works like this.  Dynamic arrays and class objects are allocated on 
the heap.  If something on the heap is reachable via a reference or 
chain of references from the stack or the static data segment, then the 
GC must hold on to it.  Otherwise, the GC will free the memory.

> Or does the array2 go out of scope when leaving the "some scope"?  
> What if the array2 is a class field?
<snip>

array2 does indeed go out of scope.  Because it's then beyond the top of 
the stack, it's no longer reachable, and so because you haven't created 
any other references to the same memory, the GC will free the memory 
when it next kicks in.

If you were to add to your some_scope block some statements that put 
references to the allocated memory somewhere else, then these will keep 
the array alive for as long as the references so created are reachable.

Stewart.


More information about the Digitalmars-d-learn mailing list