A runtime can represent values of different kinds with a tag and a union. The tag determines which union member is meaningful; it is the program’s responsibility to keep them consistent.
#include <stdio.h>
typedef enum { INT_VALUE, REAL_VALUE } Kind;
typedef struct { Kind kind; union { int integer; double real; } data; } Value;
int main(void) {
Value v = {.kind = INT_VALUE, .data.integer = 12};
if (v.kind == INT_VALUE) printf("%d\n", v.data.integer);
return 0;
}
Output is 12. The integer or real fits directly in the union; a dynamically sized string can instead have an owned character buffer. A three-component vector can contain three object pointers; an array can hold a length and a dynamically allocated array of object pointers. Both represent references to other objects, not necessarily ownership of them. For example, two array slots may refer to the same object:
array slots: [0] ──┐
[1] ──┴──> string object ──> character buffer
The slots are two separate edges, even though they point to the same object. Whether those edges keep it alive depends on the array’s ownership policy.
Constructors must initialize the tag, fields and any storage, and roll back on failure. Array access checks the object kind and index < length; a setter must specify whether it retains, borrows, or transfers its input. A getter returning a borrowed pointer becomes unsafe when the container or target is released. Type-specific length could mean one for a scalar, three for a vector, bytes before the terminator for a string, or element count for an array: these are API choices, not built-in C behavior.
Addition can dispatch on both tags: numbers yield a numeric result; two strings need combined length plus one with overflow checks; arrays can create a new pointer array referencing existing elements. Such an array copy is shallow. Vector addition may recursively create component results; if any step fails, release earlier results according to their ownership contracts. The tag is metadata, not a guarantee that its pointer fields are valid.
Building an object interface
An integer constructor allocates the wrapper, checks for null, sets kind to the integer tag and writes its integer union member. A real constructor does the same with a real member. For a string, the wrapper and its buffer are separate allocations: measure an existing terminated input, check that adding the terminator cannot overflow, allocate length + 1, copy including \0, and free the wrapper if the buffer allocation fails. The wrapper owns that buffer; the input is borrowed only during the call.
A vector’s three pointers can be stored directly in the union; the pointers represent three distinct edges even when two refer to the same target. An array wrapper holds a length and separately allocated pointer slots. Check length <= SIZE_MAX / sizeof *slots, handle length zero without depending on malloc(0), and initialize each slot by assigning NULL as a pointer value. calloc zeroes bytes but does not portably promise a null pointer representation. For construction failure, release each allocation already acquired.
A checked setter first verifies a nonnull array, its tag, and index < length. A checked getter performs the same checks and returns a borrowed pointer; a status result distinguishes an empty slot from an invalid index. Define whether null elements are allowed. A length operation can return a Boolean and put its size_t result in an output argument, avoiding a negative sentinel in an unsigned type. For the convention above, scalar length is one, vector length three, string length counts bytes before the terminator, and array length counts slots.
For addition, dispatch on both tags before reading either union member. Integer addition requires range checks before evaluating a potentially overflowing signed sum; mixed arithmetic needs an explicit conversion policy and floating-point results can round. String concatenation checks both length addition and the extra terminator before allocation. Array concatenation checks the sum of lengths and the pointer-array multiplication; it copies references, not targets. Vector addition recursively constructs three results: if a later component fails, release the earlier components. If a vector constructor retains its arguments, the caller must release its temporary owned references afterward. Unsupported combinations return failure rather than accessing the wrong union member. A production implementation also needs a policy for cyclic vectors, recursion depth, and allocator failure.
Worked runtime: ownership all the way through
The complete standalone runtime.c implements the five variants, constructors, checked array set/get, length, addition, destruction and rollback in one translation unit. It is an illustrative example, not a production library. Compile and run from this lesson’s directory (do not define NDEBUG: the demonstration uses assertions with side effects):
cc -std=c11 -Wall -Wextra -Wpedantic -Werror runtime.c -o runtime
./runtime
Expected output:
numeric, string, array and vector addition: ok
bounds, overflow and allocation rollback: ok
Follow an array addition: array(x + y) initializes every slot to a null pointer; set retains each borrowed element before storing it. The resulting array owns its slots’ references, including duplicates; it does not clone their objects. If a retain fails, release(o) walks the initialized slots, undoing every earlier retain and freeing both allocations. A failed setter leaves the old slot intact; retaining first also makes self-replacement safe. get returns a borrowed pointer and a separate status, so a valid empty slot is distinguishable from an invalid index. The caller must keep the owning container or another owner alive.
For vector addition, each recursive result starts with one owned reference. vector retains the three results, then the local references are released. If any recursive addition or constructor fails, the same cleanup loop releases every successfully created temporary; a constructor that cannot retain a later component releases its earlier edges. The built-in allocation budget tests failure at each allocation in this vector path. Integer overflow is rejected; mixed numbers convert to double, with usual rounding and floating-point behavior. Strings are copied as bytes through the terminating null, not Unicode characters; arrays concatenate shallowly. Unsupported kinds, overflow and allocation failure all return NULL without distinguishing causes.
Every successful constructor/add returns one owned reference; inputs are borrowed, and each stored edge owns one retain. Release each owned reference exactly once. Null array slots and vector components are permitted, but adding a vector with a null component fails. Counts are checked for overflow; release assumes a live owned reference and cannot validate dangling pointers. This non-atomic reference-counting example cannot reclaim strong cycles; recursive vector addition and recursive destruction assume acyclic, reasonably shallow graphs. It has no thread safety, automatic tracing integration, or general error reporting.