Skip to main content

Checked capacity arithmetic and finite evidence

What this concept is​

Element counts and allocation byte counts are different quantities. A size calculation must be valid before an allocator sees it. Unsigned wrap can be defined arithmetic while still producing a dangerously small allocation.

Why it matters here​

A buffer whose count exceeds SIZE_MAX divided by sizeof(int) cannot represent its allocation size in size_t. Growth must also avoid overflowing a doubling calculation. These are input-boundary questions before they are heap questions.

Concrete example​

The pure planner accepts current capacity, needed capacity and a limit. It rejects counts beyond the limit without changing its output. To double safely, compare against limit/2 before multiplying; near the boundary choose the limit. The tests use limits 0–16 for enumeration and a near-SIZE_MAX case without allocating giant buffers.

Common confusion / misconception​

A successful malloc call does not validate the arithmetic that produced its byte count. Sanitizers may miss a logical capacity error unless an invalid access is exercised. Near-limit tests should not depend on obtaining enormous real allocations.

How to use it​

Write the invariants length <= capacity <= SIZE_MAX / sizeof(int) and “data is NULL exactly when capacity is zero” for valid states. Separate capacity planning from allocation so arithmetic is independently testable. Combine boundary tests, fault injection, live-allocation accounting, and instrumented execution; explain what each adds.

Check yourself​

Why check the count before multiplication? Why reject append at the maximum count before adding one? Can a buffer satisfy length <= capacity while its allocation is too small because byte arithmetic wrapped?

Mini drill or application​

Use a synthetic limit of 9: plan growth from 8 to 9 and reject a request for 10 without changing the output sentinel. Then explain the equivalent byte-limit reasoning for int storage.

Read this only if stuck​

The C Programming Language for size_t and allocation; reuse the official ASan and UBSan guides for instrumentation.