Garbage Collection

Adriaan van Os gpc at
Wed Sep 3 09:43:47 CEST 2008

Prof. Harley Flanders wrote:

> Suppose I have defined
> type  Vec = array[1..1000] of Extended;  // 10,000 bytes

Not always 10,000 bytes, it depends on how many bytes an Extended has, e.g. on some platforms 8
bytes, like a double, or 16 bytes like a longdouble.

> var  A, B, C, D: Vec;
> function  Sum(const  A, B: Vec): Vec;
> In the assignment
> D := Sum(Sum(A, B), C);
> there is an intermediate result Sum(A, B), going to an unnamed temporary
> vector.

The intermediate vector will be placed on the stack.

> Does garbage collection pick up that space?

The space for the temporary vector is automatically freed, but the term "garbage collection"
<> usually refers to automatic
heap management methods, not to call stack unwinding <>.

> Similar question with
> operator  + (const  A, B: Vec) C: Vec;
> D := (A+B)+C;
> More complicated:  Delphi mode, so I have "Result" available
> var  Zero: Vec;  // Zero[J] = 0  for all  J
> function  Foo(A: Vec;  N: Word): Vec;
>  var  B: Vec;
>  begin
>  if  N = 0  then  Result := Zero
>  else  if  Odd(N)  then
>    Result := A + Foo(A, N - 1)
>  else    begin
>    B := (Foo(A, N div 2)
>    Result := B + B;
>    end;
>  end;  // Foo
> Garbage collection handles this correctly?

See the above answer.

> Whatever the answers, how do I PROVE them by measuring stack, heap, or 
> whatever?

You don't need to worry about deallocation of temporary space for function results. However, ask
yourself if there is enough stack space to put "big" function results on the stack, especially if
you are also using recursion. That depends. The alternative is to use a VAR parameter for the
result of the calculation (but be aware that a local variable will also be allocated on the call


Adriaan van Os

More information about the Gpc mailing list