# 13.2 Memory and the collector

> Objects, arrays and texts created while running live on the **heap**, and the collector recovers those nobody can reach without the program ever noticing.

Web page: https://pseudolearn.app/en/spec/motor/memoria

> **In one sentence**
>
> Objects, arrays and texts created while running live on the **heap**, and the collector recovers those nobody can reach without the program ever noticing.

## 13.2.1 How it works

A value is **alive** if it can be reached from a variable of some active frame. When it no longer can, its memory may be recovered. The program **cannot observe** when or whether that happens: there are no finalizers, no weak references and no free-memory queries.

**Figure 13.2-1: Reachable values**

The active frames point to an object, which points to another. A third object has no arrow reaching it and is marked as unreachable.

From the frames' variables two objects can be reached; the third has no path left and the collector may reuse its memory.

The proof that it is unobservable is strong: running a program collecting on **every** value creation, or never collecting, gives exactly the same output, termination and trace.

A value reachable only from variables whose block has ended —a loop body, a branch— stops counting towards the [cell limit](https://pseudolearn.app/en/spec/motor/limites.md) as soon as that block ends.

### Program: Objects created and forgotten

```pseudolearn
Class Caja
  Define valor As Integer;
EndClass

Algorithm Basura
  Define total As Integer <- 0;
  For i <- 1 To 1000 Do
    Define c As Caja <- New Caja();
    c.valor <- i;
    total <- total + c.valor;
  EndFor
  Write total;
EndAlgorithm
```

**Output**

```text
500500
```

*The program finishes normally.*

Every round creates a box that stops being reachable when the round ends. Suspended tasks are roots too: what their frames hold, their pending results and the channels' messages stay alive as long as needed.

**In short**
- Values created while running live on the heap.
- What cannot be reached is recovered, with no observable effect.
- Collecting always or never gives the same run.

**See also**
- [9.6 Copies, references and identity](https://pseudolearn.app/en/spec/objetos/copia.md)
- [13.6 Engine limits](https://pseudolearn.app/en/spec/motor/limites.md)
