1.3 C: memory, pointers, structs, headers, and the C11 toolchain
In Python, a[7] on a 6-element list raises IndexError. In C, A[7] on a 6-element array reads whatever 4 bytes happen to follow it, quietly, and a kernel can return a plausible number that is wrong. In C, a buffer nobody frees leaks, and one freed twice corrupts the allocator. The C material in these books consists of optional standalone exercises, and every one of them assumes you carry C’s model of memory in your head and build with the tools that catch its failures.
Concepts from other sections (3)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Geometric growth: multiplying the capacity by a constant factor when full, which makes appends amortized. Read more: 15.1 A growable array
- Geometric sum: the sum of the first terms, for and for . Read more: 6.3 Sequences, geometric series, and frequency ladders in Mathematics
- Move semantics: transferring the resources of an object that is about to be discarded (an rvalue) to a new owner by taking its pointers instead of copying what they point at;
std::movecasts a value to an rvalue to request it. Read more: Chapter 19: C++
This section gives you that model and those tools, on an exercise small enough to reason about completely: a growable array of int, written as vec.c against the given header vec.h, with six functions vec_init, vec_reserve, vec_push, vec_pop, vec_get, and vec_free. The header is the whole contract; there is no other.
It builds on Python and numpy, whose arrays are the buffers later handed to C as row-major bytes with strides, and on Shell, git, make, and processes, which covered compiling, linking, make, and exit codes. A C test binary is a process whose exit status is the verdict.
Learning objectives
- Compute pointer arithmetic, indexing, and struct layouts with padding by hand.
- Distinguish automatic, static, and allocated storage, and state who owns and frees each block.
- Use
reallocsafely: keep the old pointer until it succeeds, and grow geometrically for amortized O(1) pushes.- Recognize undefined behavior and build with AddressSanitizer and UndefinedBehaviorSanitizer to catch it.
- Explain declarations, definitions, headers, include guards, and linkage across translation units.
Notation
Section titled “Notation”The section uses the following notation throughout.
| Symbol | Meaning | Type / shape |
|---|---|---|
T | any C type (int, float, a struct) | |
sizeof(T) | bytes one object of type T occupies | size_t |
_Alignof(T) | T’s alignment: its address must be a multiple of this | size_t, a power of two |
&x | the address of object x | T * |
*p | the object at address p | T |
p + i | the address | T * |
p[i] | the same as *(p + i) | T |
offsetof(S, f) | bytes from the start of struct S to its field f | size_t |
| the smallest multiple of that is : | integer | |
| , , | element counts in the growable array | size_t |
Bytes, addresses, and types
Section titled “Bytes, addresses, and types”Memory, as a C program sees it, is one long array of bytes. Each byte has an address, an integer (on a 64-bit machine, 64 bits wide). A C object is a run of consecutive bytes, and its type says how many and how to read them. The common types have these sizes:
| Type | sizeof on a 64-bit Mac or Linux | Holds |
|---|---|---|
char, int8_t, uint8_t | 1 | a byte |
int32_t, uint32_t, float | 4 | a 32-bit integer; a 32-bit IEEE 754 float |
int64_t, uint64_t, double | 8 | a 64-bit integer; a 64-bit float |
int | 4 (the standard only promises at least 2) | the “natural” integer |
size_t | 8 | a size or an index; unsigned, so 0 - 1 wraps to the largest value |
any pointer T * | 8 | an address |
Use the fixed-width types from <stdint.h> (int32_t, int64_t) whenever the width matters, which is always at a language boundary: Python and Rust must agree with C on every byte.
Pointers and pointer arithmetic
Section titled “Pointers and pointer arithmetic”A pointer T *p holds an address and remembers the type at that address. A C pointer is one of those byte addresses plus the type of what lives there. &x takes the address of x; *p is the object at p. NULL is the address no object has; dereferencing it is an error. Arithmetic on a pointer counts in elements, not bytes: if p points at an int32_t at address 4096, p + 3 is 4096 + 3 · 4 = 4108. Indexing is defined as arithmetic: p[i] means *(p + i), the object i * sizeof(*p) bytes past p.
An array int32_t xs[5] is 5 objects back to back, 20 bytes. In almost every expression the array’s name decays to a pointer to its first element, which is why a function that takes const int32_t *xs can receive an array, and why it must also receive the length separately: the pointer does not carry it. const T *p promises the function will not write through p; the compiler enforces it.
A matrix is stored the same way, as one flat run of numbers. Row-major order puts row 0 first, then row 1, so element of an matrix is A[i * K + k]. The matmul exercise in Mathematics builds on exactly this.
Structs, alignment, and padding
Section titled “Structs, alignment, and padding”Pointers explain how to find one object; structs explain how several fit together. A struct groups fields into one object. The hardware reads an 8-byte double fastest (on some machines, only) at an address that is a multiple of 8, so every type has an alignment, and the compiler places each field at the next offset that is a multiple of the field’s alignment:
The unused bytes between fields are padding. The struct’s own alignment is its largest field alignment, and its size is rounded up to a multiple of that, so that in an array of structs every element’s fields stay aligned. The compiler never reorders fields. So {int32_t id; double score;} is 16 bytes with score at offset 8: id takes bytes 0 to 3, score must start at , and the total is already a multiple of 8. Python must mirror that layout field for field when it reads such a struct.
Where objects live: stack, static, heap
Section titled “Where objects live: stack, static, heap”Every object also has a lifetime, decided by where it is stored. There are three kinds of storage:
| Storage | How you get it | Lifetime |
|---|---|---|
| automatic (“the stack”) | a local variable float x[4]; | until the function returns; a pointer to it afterwards dangles |
| static | a variable at file scope, or static inside a function | the whole program |
| allocated (“the heap”) | malloc(n), calloc(k, n), realloc(p, n) | until you free(p) |
malloc(n) returns a pointer to n fresh, uninitialized bytes, or NULL when it cannot. free(p) gives them back; free(NULL) does nothing. Ownership is the rule you keep in your head: exactly one piece of code is responsible for freeing each block, exactly once.
realloc(p, n) resizes the block at p to n bytes. It may grow it in place, or allocate a new block, copy the old bytes, free the old block, and return the new address: every pointer into the old block is then dangling. If it fails it returns NULL and leaves the old block untouched and still yours. realloc(NULL, n) is malloc(n). realloc(p, 0) is implementation-defined in C11 and undefined in C23: do not use it.
A growable array keeps elements in a buffer of capacity . When a push finds it must grow. Growing by a constant copies elements every pushes, about copies for pushes. Growing by a factor (doubling, ) copies at most elements in total, a constant amount per push on average (amortized O(1)). That is why realloc-based growth must be geometric: grow by a constant and pushing elements costs .
Undefined behavior and the sanitizers
Section titled “Undefined behavior and the sanitizers”Getting lifetimes or bounds wrong does not raise an error in C, because C checks nothing at run time. The C standard lists operations whose result is undefined: reading or writing outside an object, using memory after free, freeing twice, dereferencing NULL, reading an uninitialized variable, overflowing a signed integer (int32_t 2,000,000,000 + 2,000,000,000), shifting by the width or more. “Undefined” does not mean “crashes”. The compiler optimizes on the assumption that it never happens, so the program may appear to work, return a wrong number, or fail somewhere far away. Unsigned arithmetic (size_t, uint32_t) is defined: it wraps around modulo .
Two compiler-inserted checkers turn most of it into a crash with a report at run time, so C code in these books is built and tested with them on:
| Flag | Name | Catches |
|---|---|---|
-fsanitize=address | AddressSanitizer (ASan) | out-of-bounds reads and writes on heap, stack, and globals; use after free; double free. It surrounds every block with poisoned “redzones” and keeps freed memory poisoned for a while |
-fsanitize=undefined | UndefinedBehaviorSanitizer (UBSan) | signed overflow, misaligned pointers, NULL dereference, bad shifts, out-of-range conversions |
-fno-sanitize-recover=undefined | make UBSan stop the program at the first report instead of printing and continuing |
Apple’s clang has no LeakSanitizer (the Linux leak checker), so leaks are detected by counting allocations: a test build routes the code’s malloc, realloc, and free through wrappers (pasted in with -include) that keep a live-block count, and fails any test that ends above zero.
Headers, declarations, and linkage
Section titled “Headers, declarations, and linkage”The last piece is how separately compiled files agree with each other. The previous section showed the two build stages: compile each .c to an object file, then link the objects. What crosses between files is names:
- A declaration says a name exists and what its type is:
int vec_push(Vec *v, int x);. A definition creates it: the function with its body, or a variable with its storage. A name may be declared many times and defined once. - A header is a file of declarations that every
.cusing them#includes. The preprocessor pastes it in textually, so a header is protected by an include guard (#ifndef VEC_H/#define VEC_H/#endif) against being pasted twice into one file. - Linkage decides who can see a name. A function or file-scope variable has external linkage by default: its name is exported from the object file as a symbol, and the linker resolves every other file’s use of it. Marked
static, it has internal linkage: visible only inside its own file, and no symbol is exported.
nm file.o lists an object’s symbols: T for a function defined here and U for one used here but defined elsewhere. On macOS every C symbol carries a leading underscore (_vec_push).
A header is therefore a contract between C translation units. Include it in both the implementation and the test program; a missing or mismatched declaration then becomes a compiler error rather than a silent disagreement at link time. The optional C exercises link the resulting objects into standalone test executables, which keeps each exercise testable without loading a native library into another language runtime.
The flags the build uses
Section titled “The flags the build uses”The test builds combine all of this into one command line. Each flag has a job:
| Flag | Meaning |
|---|---|
-std=c11 | compile as ISO C11 (the C these books use) |
-pedantic | warn about anything C11 does not allow, including compiler extensions |
-Wall -Wextra | the common warnings and then some |
-Werror | treat every warning as an error: a warning is a bug you have not found yet |
-Wno-unused-parameter | except one: a parameter a function does not read yet (a stub’s) is allowed |
-O1 -g | light optimization (sanitizers need some) with debug information for readable reports |
-c, -o out | compile only (stop at the object file, for example to link into a standalone test binary); name the output |
-I dir | also look in dir for #include "..." |
-include file.h | paste file.h at the top of the source before anything else (a test build uses it to wrap malloc) |
Working it by hand
Section titled “Working it by hand”Now trace the growable array before writing it. Start from vec_init (, data == NULL) and push 10, 20, 30, 40, 50, doubling from a first capacity of 4:
| Push | before | before | Grows? | Call | after | Buffer bytes |
|---|---|---|---|---|---|---|
| 10 | 0 | 0 | yes | realloc(NULL, 16) (a malloc) | 4 | 16 |
| 20 | 1 | 4 | no | 4 | 16 | |
| 30 | 2 | 4 | no | 4 | 16 | |
| 40 | 3 | 4 | no | 4 | 16 | |
| 50 | 4 | 4 | yes | realloc(data, 32): may move, copies 16 bytes | 8 | 32 |
After three pushes, vec_get(&v, 1) reads *(data + 1), the 4 bytes at data + 4: 20. This is the first test case. If realloc at push 50 had failed, it would return NULL with the 16-byte block still holding 10, 20, 30, 40, which is why the old pointer must survive the call.
The interface
Section titled “The interface”Two files sit in primers/lang.03/. vec.h is given: it holds the Vec struct and six functions, each with its contract in a comment. vec.c is the solution: their definitions, using the standard library only, doubling the capacity from 4.
typedef struct { int *data; /* the buffer, NULL until the first allocation */ size_t len; /* elements in use */ size_t cap; /* elements the buffer can hold */} Vec;
void vec_init(Vec *v); /* zero state; allocates nothing */int vec_push(Vec *v, int x); /* 0, or -1 on allocation failure with v unchanged */int vec_pop(Vec *v, int *out); /* 0, or -1 if empty */int vec_get(const Vec *v, size_t i); /* i >= len is undefined behavior, on purpose */int vec_reserve(Vec *v, size_t n); /* capacity >= n, len unchanged; -1 on failure, v unchanged */void vec_free(Vec *v); /* release and return to the zero state; safe twice */A test build compiles vec.c with -std=c11 -pedantic -Wall -Wextra -Wno-unused-parameter -Werror under ASan and UBSan, with -include of a header that wraps the allocator in counters, and links it into a standalone C test binary.
Building it step by step
Section titled “Building it step by step”Seven observations determine the code. Try to write each function before reading it.
- The zero state must be valid and free: a vector that is never pushed to should never call the allocator. So
vec_initonly setsdata = NULL, len = cap = 0, and every other function must accept that state.realloc(NULL, n)behaving asmalloc(n)andfree(NULL)doing nothing are what make that possible without special cases. - Amortized O(1) pushes require geometric growth. Doubling from a first capacity of 4 gives the hand-worked table and, for 4,096 pushes, only allocations.
- All growth goes through one function.
vec_pushgrowing by one slot andvec_reservegrowing tonare the same operation (“ensure capacity for at least n”), sovec_pushcallsvec_reserve(v, len + 1)and the doubling rule lives in one place. reallocmay fail, and the contract says a failed push or reserve leavesvunchanged. So the result goes into a temporary, andvis updated only after it is known to be non-NULL.- Sizes are
size_t, which wraps silently. Two multiplications can wrap: doublingcap, andcap * sizeof(int). A wrapped byte count would allocate a tiny block and the next writes would overrun it. Both must be checked before they happen. vec_popon an empty vector must not computelen - 1, which wraps to . The emptiness check comes first.vec_freemust make a second call harmless and leave the vector reusable: free, then reset to the zero state of step 1.
Initialization
Section titled “Initialization”void vec_init(Vec *v) { v->data = NULL; /* no buffer until the first push: step 1 */ v->len = 0; v->cap = 0;}Reserve: the one place memory grows
Section titled “Reserve: the one place memory grows”int vec_reserve(Vec *v, size_t n) { if (n <= v->cap) return 0; /* never shrinks; nothing to do */ /* Double, starting at 4, until the request fits. */ size_t cap = v->cap ? v->cap : 4; while (cap < n) { if (cap > SIZE_MAX / 2) { /* doubling would wrap around */ cap = n; /* fall back to exactly what was asked */ break; } cap *= 2; } if (cap > SIZE_MAX / sizeof(int)) return -1; /* cap * sizeof(int) would wrap */ /* Keep the old pointer until realloc succeeds: `v->data = realloc(...)` * loses (and leaks) the buffer when realloc returns NULL. */ int *grown = realloc(v->data, cap * sizeof(int)); if (grown == NULL) return -1; /* v untouched: same data, len, cap (step 4) */ v->data = grown; /* the old address may now be dangling */ v->cap = cap; return 0;}The overflow checks compare against SIZE_MAX / 2 and SIZE_MAX / sizeof(int) instead of multiplying and checking afterwards, because after an unsigned multiply wraps the evidence is gone (step 5). The loop doubles until the request fits, so vec_reserve(&v, 100) on an empty vector goes 4, 8, …, 128 and allocates once, not seven times. The first push in the hand trace is vec_reserve(v, 1) with cap = 0: cap starts at 4, the loop does not run, and realloc(NULL, 16) acts as malloc(16). The fifth push is vec_reserve(v, 5) with cap = 4: one doubling to 8, realloc(data, 32).
Push and pop
Section titled “Push and pop”int vec_push(Vec *v, int x) { /* grow only when full; && skips vec_reserve when there is room */ if (v->len == v->cap && vec_reserve(v, v->len + 1) != 0) return -1; v->data[v->len++] = x; /* write at len, then count it */ return 0;}
int vec_pop(Vec *v, int *out) { if (v->len == 0) return -1; /* before any len - 1: step 6 */ *out = v->data[--v->len]; /* decrement first: the last element is at len - 1 */ return 0;}vec_push asks for len + 1, and vec_reserve rounds that up by doubling, so the rule from step 3 holds. If growth fails, the function returns before writing, so len and the buffer are as they were. vec_pop returns through an out-parameter so that -1 can mean “empty” without stealing a value from the element range: every int is a valid element.
Get and free
Section titled “Get and free”int vec_get(const Vec *v, size_t i) { return v->data[i]; /* no bounds check, by contract: ASan catches misuse in tests */}
void vec_free(Vec *v) { free(v->data); /* free(NULL) is defined to do nothing */ v->data = NULL; /* a second vec_free then frees NULL: harmless */ v->len = 0; v->cap = 0; /* back to the zero state: the vector is reusable */}vec_get takes const Vec *, promising not to modify the vector, so it can be called on a read-only view. The header says reading past len is undefined behavior on purpose: a bounds check on every access is a cost a hot loop should not pay, and under the sanitizers a test that reads out of bounds still fails loudly.
The full solution is vec.c, written against vec.h.
Why this design
Section titled “Why this design”In cost, vec_push is amortized O(1): pushes copy at most elements in total (the geometric sum with ). vec_get and vec_pop are O(1). Memory overhead is at most a factor of 2 over the elements in use.
Doubling, rather than CPython’s factor of about 1.125, means fewer reallocations at the cost of up to half the buffer unused. For a primer and for the buffers in these books, simplicity and few copies win. Having one growth function, rather than duplicating the doubling in vec_push, means the overflow checks and the failure rule exist once, so there is one place to get them right. The vector never shrinks: vec_pop never gives memory back, because shrinking on pop risks thrashing (grow, shrink, grow at a boundary); a caller who wants the memory back calls vec_free. And one tradeoff is accepted deliberately: vec_get is unchecked. Correct callers pay nothing; incorrect ones are caught by ASan in tests rather than by a branch in production.
What can go wrong
Section titled “What can go wrong”The tests probe each promise in the header. vec_init must set the zero state and call no allocator. The pushes from the hand trace must read back in order with nothing leaked. vec_pop must be last in, first out, and return -1 on an empty vector. vec_reserve must grow capacity ahead without changing length, and must never shrink. Growth must preserve every element through many moves (10,000 pushes keep every value) and must be geometric (4,096 pushes take at most 40 reallocations). A failing realloc, injected by the counting wrappers, must make the call return -1 and leave data, len, and cap as they were. And a second vec_free must be harmless, with the vector reusable afterwards.
The mistakes that break these cases are few and classic:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
v->data = realloc(v->data, ...) | when realloc fails, the only pointer to the old buffer is lost: the elements are gone and the block leaks | realloc into a local grown; v->data is assigned only after success |
| growing by one (or any constant) | correct but quadratic: a million pushes take seconds | vec_reserve doubles from 4 |
vec_pop reading data[len - 1] without checking len | len - 1 on a size_t 0 wraps to ; ASan reports a wild read | vec_pop returns -1 when len == 0 before touching the buffer |
vec_free leaving data set | the second call frees the same block twice | vec_free sets data to NULL, and free(NULL) does nothing |
Warning: Never assign
realloc’s result straight back to the only pointer you hold. On failure you lose the block and leak it in one line.
Where this leads
Section titled “Where this leads”This primer has no code call site of its own; it introduces C memory and standalone C tests, and the optional C sections elsewhere remain independent exercises with their own sanitizer-enabled test binaries. In Mathematics, Vectors, matrices, row-major layout, and matmul has an optional matmul exercise over const float * buffers with explicit leading dimensions, run under sanitizers. In Algorithms, the growable array tl_vec generalizes this vector to a type-erased element, again checked as standalone C. The next section, Rust, shows how a language can enforce at compile time the ownership rules you kept in your head here.
Further reading
Section titled “Further reading”- Jens Gustedt, Modern C (free), levels 1 and 2.
- Kernighan and Ritchie, The C Programming Language, chapters 5 and 6.
- The C11 draft N1570 (free): 6.2.5 types, 6.5.6 pointer arithmetic, 6.7.2.1 structs, 7.22.3 memory management.
- CPython
Objects/listobject.c,list_resize: grows by about 1.125 plus a constant, trading more frequent copies for less unused memory. - Rust
alloc/src/raw_vec.rsand the libstdc++ and MSVC STL sources:Vec<T>andstd::vector<T>add generic element types, move semantics, and a growth factor of 2 (Rust) or 1.5 (MSVC). - jemalloc and mimalloc statistics (
MALLOC_CONF=stats_print:true) and LeakSanitizer (ASAN_OPTIONS=detect_leaks=1): per-size-class counters and leak reports with stack traces (Linux), the production versions of the counting wrappers.
Key terms
Section titled “Key terms”- pointer: an address plus the type of the object at that address.
- decay: the conversion of an array’s name to a pointer to its first element.
- alignment: the power of two that an object’s address must be a multiple of.
- padding: unused bytes the compiler inserts so each struct field is aligned.
- ownership: the rule that exactly one piece of code frees each allocated block, exactly once.
- amortized O(1): constant average cost per operation over a long sequence, as with geometric growth.
- undefined behavior: an operation the C standard gives no meaning to, which the compiler assumes never happens.
- linkage: whether a name is visible outside its translation unit (external) or only inside it (internal,
static).
Summary
Section titled “Summary”- Memory is a sequence of bytes with numeric addresses;
p[i]is the objecti * sizeof(*p)bytes pastp. - C checks nothing at run time: out-of-bounds access, use after free, and signed overflow are undefined behavior, so build and test with ASan and UBSan.
reallocmay move the buffer and may fail; keep the old pointer until it succeeds, and grow geometrically, or pushes cost .- A struct has padding:
{int32_t id; double score;}is 16 bytes withscoreat offset 8, and Python must mirror that layout field for field. - A header is a contract between translation units; include it in both the implementation and the test so the compiler checks declarations against definitions.
Review questions
Section titled “Review questions”-
Why does
vec_reserveassignrealloc’s result togrownand not straight tov->data?Answer
If
reallocfails it returns NULL and leaves the old block allocated. Writing NULL intov->datawould lose the only pointer to that block: the elements would be unreachable and the block would leak, violating “v is unchanged and still valid”. -
Why is the overflow check
cap > SIZE_MAX / sizeof(int)rather thancap * sizeof(int) < cap?Answer
Dividing the limit cannot overflow, so the check is exact. Checking after the multiply relies on the wrapped value being smaller, which holds for some wraps but not all (a product can wrap past the original value). Comparing before multiplying avoids reasoning about wrapped values at all.
-
What does
vec_popdo on an empty vector, and what wouldv->data[v->len - 1]have done?Answer
It returns
-1without touching memory.v->len - 1withlen == 0isSIZE_MAXfor an unsignedsize_t, so the read would be far outside the buffer (or through NULL): undefined behavior that ASan reports as a wild read. -
Why is calling
vec_freetwice safe?Answer
The first call frees the buffer and sets
datato NULL. The second call passes NULL tofree, which the C standard defines as doing nothing. Without the reset, the second call would free the same block twice. -
How many times does
reallocrun for 4,096 pushes, starting fromvec_init?Answer
Capacities go 4, 8, 16, …, 4096: that is 11 allocations ( to ), well under the 40 the growth case allows. Growing by one would take 4,096.