Skip to main content

Memory, Pointers, and Representation: Worked Examples

Work through each trace before reading the explanation. Then solve the transfer task without the page open.

Example 1: A valid address can outlive its object​

A function returns the address of a local integer. The pointer value can be copied to its caller, but the automatic object's lifetime ended on return. Reading through it is invalid even if a trial run prints the expected value.

Return the integer by value, accept caller-provided storage, or allocate with an explicit ownership contract. The right choice depends on size and lifetime. “It still prints 7” is not evidence that the lifetime rule was satisfied.

Example 2: Reallocation changes the alias problem​

A grows dynamically; B points to an element inside A. Reallocation may move the storage, invalidating B. Even retaining the old numerical address does not preserve the old object's validity after successful reallocation.

Store an index when possible, then reconstruct the element pointer from the current base after a successful resize. Keep the original allocation pointer until failure has been checked. Allocation failure and alias invalidation are separate obligations.

Transfer and self-check​

If a resize fails, should the program replace its only owning pointer with the returned null value? Check: no; doing so loses access to the original allocation.

Evidence to keep​

Save your first attempt, corrected reasoning, and transfer result as checkpoint evidence. A matching final answer without an explanation is insufficient. Continue with the guided lab and use the reading guide to repair a specific gap.