Skip to main content

Failure-atomic allocation and publication

What this concept is​

Failure atomicity means a failed operation leaves the promised observable state unchanged. For this lab, failed reserve or append preserves data, length and capacity. It is a contract to design, not a property obtained merely by checking for NULL.

Why it matters here​

Real allocation failure is difficult to reproduce reliably. An injected allocator can fail one chosen request, making recovery testable without trying to exhaust the computer’s memory.

Concrete example​

The reference reserves new storage, copies only initialized elements, then releases old storage and publishes the new pointer/capacity. If allocation fails, it returns before changing the owner. The payload is int, so copying cannot invoke a user callback that fails. A generalized element type would need a different contract. The temporary peak storage includes both old and new buffers.

Common confusion / misconception​

Overwriting the only owner pointer with a failed allocation result loses recovery information. Conversely, releasing old storage before obtaining the replacement makes preservation impossible. The familiar realloc API has its own lifetime rules; do not assume a successful call preserves borrowed pointers merely because the address looks unchanged.

How to use it​

Identify a prepare phase, operations that can fail, and the point at which the new state becomes visible. Keep changes to length until reserve succeeds. Inject failures at successive allocation requests and retry after each. Count live allocations and validate cleanup rather than assuming every allocation attempt creates an object.

Check yourself​

Why does a failed allocation attempt need no release? Which state must remain unchanged when the fifth push fails? What extra memory does allocate-copy-release require during growth?

Mini drill or application​

Arrange failure on allocation request 2. Append values until growth is needed, retain the failure output and invariant checks, then retry. Draw the owner before failure and after recovery.

Read this only if stuck​

The C Programming Language for allocation, and N1570 section 7.22.3.5 when comparing realloc semantics. The lab deliberately uses separate allocate and release callbacks.