Terminology (4)Terms used in this lesson
Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.
- Automatic storage
- In the native automatic-storage model, storage associated with a block or call scope rather than an independent allocation. Compilers need not materialize every local in a physical frame.
- Dynamic storage
- Storage allocated while the program runs that lasts until it is released; usually on a heap.
- Frame
- A model of one active call’s state, often implemented with stack storage. Inlining and optimization can change or eliminate it.
- Reference counting
- Tracking strong owners of a managed value or logical slot so its last release can trigger cleanup or reuse. Weak bookkeeping storage can have a longer lifetime.
Storage and lifetime
The stack is a model of nested function calls: each active call has a frame for its temporary state. Heap storage is allocated during execution and can have a lifetime independent of the call that requested it. A source-level local does not by itself tell you which physical storage an optimized program uses.
Lifetime asks how long a value can be used safely; ownership and reachability help determine when its storage can be released. A reference or view gives access to existing storage. Keeping that access valid and keeping its contents unchanged are separate requirements.
01Outliving a call
Where does a value that outlives its call live?
The shipping desk keeps labels for later printing. The formatter returns, another order arrives, and an earlier label changes. Follow the result beyond its creating call: which storage remains usable, who can overwrite it, and when may a shared label slot be reused?
Start with one label leaving the formatter. A call frame is a useful model for temporary call state, but a local binding and the value it reaches can have different lifetimes. Returning an owned value can construct or move the result into the caller’s storage; it does not inherently require a separate heap allocation. Dynamic storage is another way to give data a lifetime independent of the creating scope.
Each program creates a label inside a function and gives the caller access to it. Predict the language-level result first; the examples do not measure physical stack or heap addresses.
JavaScript object references can remain usable after the function returns. Unreachable objects become eligible for collection, with no promised collection deadline or exposed physical placement.
// A function creates a label and hands it back to the caller.
type Label = {
text: string;
};
function makeLabel(order: string): Label {
const label: Label = { text: `order ${order}` };
return label;
}
const first = makeLabel("A");
const second = makeLabel("B");
console.log(first.text, "|", second.text);
npx tsc main.ts --noEmit --strict && node main.ts
Put each example in the shown file and run the command. The C++ command uses -Werror so that a warning about a returned local stops the build. Several Rust and C++ examples are expected to be rejected.
02Reuse
What happens when storage is reused between calls?
The label can survive return and still fail the archive’s next requirement: its contents must survive the next formatting call. Reusing a buffer can reduce allocations, but a returned view still observes that buffer. A retained result needs independent contents or an explicit lifetime during which the shared buffer will not be overwritten.
format returns the same module-level array every time.
// A formatter reuses one array between calls.
const buffer: string[] = [];
function format(order: string): string[] {
buffer.length = 0;
buffer.push(`order ${order}`);
return buffer;
}
const first = format("A");
const second = format("B");
console.log(first[0], "|", second[0]);
03Release
Who releases dynamic storage?
Now several active orders intentionally share one label. The contents can stay immutable, but the slot cannot be reused when just the first order finishes. Garbage collection tracks reachability; ownership and explicit pool bookkeeping answer different lifetime questions. Strong reference counts can record how many owners still require a managed value.
| Language | One owner | Shared |
|---|---|---|
| TypeScript | Eligible for garbage collection once unreachable; no immediate collection guarantee | Same: reachability covers sharing |
| Go | Eligible for garbage collection once unreachable; no immediate collection guarantee | Same: reachability covers sharing |
| Rust | An owned value is dropped normally; Box releases its owned allocation | Rc/Arc drop the managed value at the last strong owner; weak owners can retain backing storage |
| C++ | Automatic owners run destructors normally; unique_ptr or explicit delete can release an owned allocation | shared_ptr invokes its deleter at the last strong owner; weak_ptr can retain control-block storage |
04Practice
Finish the shipping label program
The lab is one shipping label program. It reads orders from stdin and prints their labels. Each level supplies the parts that already work.
The shipping label program
Format a label, keep each label, then release shared labels at the right time.
In the frontend Trace who owns a shared download URL when one view unmounts. Optional
Two mounted label-download views receive the same Blob URL from their parent. Each keeps that URL unchanged for its lifetime. This diagnostic component revokes it during its own cleanup. Remove one view while the other still offers its link: can the remaining URL string preserve the resource for a later download?
"use client";
import { useEffect } from "react";
export default function LabelDownload({ url }: { url: string }) {
useEffect(() => {
return () => URL.revokeObjectURL(url);
}, [url]);
return (
<a href={url} download="label.txt">
Download label
</a>
);
}
A URL string is not an owner count for the browser’s Blob URL store. After this authorized revocation, a new dereference through the other view’s link has no live entry; a request started before revocation can still complete. React cleanup also runs before a changed dependency is set up, and development Strict Mode can run an extra setup/cleanup cycle. Decide which lifetime owns the shared URL; this view currently releases a resource another view may still need.
Sources: File API: creating and revoking Blob URLs,React: effect cleanup,Svelte: onMount cleanup.
Sign in to keep your read marks on every device. Sign in
Was this helpful?