Skip to main content

Owning buffers and borrowed element pointers

What this concept is​

An owning buffer controls an allocation’s lifetime. A borrowed element pointer permits access only while its referent remains alive and the operation is within bounds. Copying an address does not create a second allocation or a second owner.

Why it matters here​

A growable array combines ordinary indexing with changing storage. A correct append can invalidate earlier element pointers even when the logical element still exists. This connects Semester 3 ownership contracts to actual C object lifetimes.

Concrete example​

Keep index 2 while a buffer grows from capacity 4 to 8. After successful growth, read through b.data[2], not a saved pointer into the old allocation. On allocation failure, the old allocation remains live under this lab’s contract, so its data and borrows remain unchanged. The passing tests compare saved owner pointers only on failure, never after successful release.

Common confusion / misconception​

A numerically familiar address is not proof of a live object. The owning struct must not be shallow-copied and independently destroyed. Setting one pointer to NULL does not repair all aliases. Zeroing the owner after destruction provides a repeatable empty state, not immunity for stale borrowed pointers.

How to use it​

Draw owner, allocation, initialized range and any borrowed views. Label the event that ends each borrow. Pass scalar values or stable logical indices through operations that may grow. Require allocator context to outlive the owner and final cleanup. Do not dereference stale pointers just to “see whether it works.”

Check yourself​

Which survives growth: a value copied into a local int, an index, or an element pointer? What happens if two shallow-copied owners both free the allocation?

Mini drill or application​

Trace init, push four values, retain index 1, append a fifth, reacquire element 1, destroy, destroy again. Annotate every ownership transition without evaluating an expired pointer.

Read this only if stuck​

The C Programming Language for pointer/lifetime reasoning; the lab header defines the ownership contract used here.