Reading complete programs through their contracts
Connect validation, objects, arithmetic, state changes, and output through two worked C17 programs.
In this chapter9 sections
A complete program connects several small rules. Read it by asking what inputs it accepts, what each step may change, and how it reports failure. The examples here connect the theory; Codeweek provides longer line-by-line practice.
1. Read a program in four passes
- State the job. Identify accepted input and the required result.
- Draw the data contract. Name live objects, accessible regions, ownership, and permitted mutation.
- Follow decisions and updates. Check validation before an operation relies on it.
- Follow failure and cleanup. Explain what state survives rejection and which acquired resources must be released.
A successful demonstration confirms only the checked case. It does not prove every input, implementation, schedule, or environment. Keep the contract beside the example so changing one assumption does not silently invalidate the reasoning.
2. A sum that commits its result only on success
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <limits.h>
static bool sum_values(const unsigned *values, size_t count,
unsigned *result)
{
if (result == NULL || (values == NULL && count != 0)) return false;
unsigned total = 0;
for (size_t i = 0; i < count; ++i) {
if (values[i] > UINT_MAX - total) return false;
total += values[i];
}
*result = total;
return true;
}
int main(void)
{
const unsigned values[3] = { 10, 20, 30 };
unsigned result = 999;
bool accepted = sum_values(values, 3, &result);
assert(accepted && result == 60);
const unsigned too_large[2] = { UINT_MAX, 1 };
result = 77;
bool rejected = sum_values(too_large, 2, &result);
assert(!rejected && result == 77);
bool empty = sum_values(NULL, 0, &result);
assert(empty && result == 0);
bool absent_input = sum_values(NULL, 1, &result);
assert(!absent_input && result == 0);
bool absent_result = sum_values(values, 3, NULL);
assert(!absent_result);
return 0;
}
The input is a region of count readable unsigned objects, or a null pointer when count is zero. Result designates a live writable unsigned destination. The function borrows the input; it neither allocates nor frees that region. A pointer type and null check cannot prove that a caller supplied a real region of the promised length.
Total starts at zero. Before adding values[i], the comparison proves the mathematical result will fit in unsigned. Unsigned wrap would be defined, but the application rejects loss of the intended sum. Result is written only after the loop, so an overflow rejection preserves the caller’s previous destination value.
The program checks a normal sum, an overflow rejection with a sentinel result, an empty region, a missing nonempty input, and a missing result. Notice that function calls happen before assert; disabling assertions must not remove the operation being demonstrated. See operators, array/count contracts, and defensive boundaries for the individual rules.
3. A small input workflow with an explicit grammar
The application accepts one command-line argument: one to three decimal digits whose value is 0 through 100. Leading zeroes are allowed within the length limit; signs, whitespace, trailing text, and longer spellings are rejected. This is an application policy, not a description of every string strtol itself accepts.
Read the complete C17 workflow
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
static bool parse_level(const char *text, int *result)
{
if (text == NULL || result == NULL || text[0] == '\0') return false;
size_t length = 0;
for (; text[length] != '\0'; ++length) {
if (length == 3 || text[length] < '0' || text[length] > '9') {
return false;
}
}
errno = 0;
char *end;
long candidate = strtol(text, &end, 10);
if (errno == ERANGE || *end != '\0' || candidate < 0 || candidate > 100) {
return false;
}
*result = (int)candidate;
return true;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fputs("Usage: level VALUE\n", stderr);
return EXIT_FAILURE;
}
int level = 0;
if (!parse_level(argv[1], &level)) {
fputs("Use one to three digits, with value 0 through 100.\n", stderr);
return EXIT_FAILURE;
}
if (printf("level=%d\n", level) < 0 || fflush(stdout) == EOF) {
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
parse_level first rejects missing destinations and empty text, then validates the spelling and length. It converts only after that grammar is established, checks conversion status and the domain, and narrows to int only after proving 0 through 100. The destination changes once, on acceptance. Its source contract still requires a valid null-terminated string; this function cannot inspect an arbitrary dangling pointer safely.
In main, argc is checked before argv[1] is used. Input errors go to stderr and select failure. Accepted input produces a labelled value, and the required output is checked and flushed. Successful flushing is a host-stream observation, not a promise of physical durability at an external destination.
| Argument | Decision | Reason |
|---|---|---|
| 42 | Accept: level=42 | Grammar, length, and domain all hold. |
| 001 | Accept: level=1 | Leading zeroes are allowed; base 10 is explicit. |
| 101 | Reject | Valid digit spelling, outside the application range. |
| +1 or 1 followed by a letter | Reject | The grammar is narrower than general strtol syntax. |
| 0000 | Reject | Value alone does not satisfy the three-character spelling limit. |
Revisit command-line arguments, parsing, and output contracts to review each boundary. A larger application could separate diagnostics and policy further; the small program keeps them visible in one place.
4. Change one assumption and recheck the connected rules
If the sum now accepts signed negative values, the unsigned-domain proof is no longer the required proof. If the input format allows spaces or a larger range, the grammar, conversion/range checks, diagnostics, and examples must change together. If buffers become shared by threads, const access alone does not synchronize them.
For an allocating variant, define who owns the returned storage and the exact release operation. For a file variant, review acquisition, transfer, close, and partial-output behavior. These are connected design decisions, not details that can be filled in by adding a cast or suppressing a warning.
5. How to use the earlier example collection
The retained collection below includes nine complete programs: greeting, arithmetic, FizzBuzz, bounded factorial, arrays, a linked list, growing allocation, controlled file I/O, and macro examples. Read them as illustrations with the stated limits. The factorial is for small n; the file reader reads the small integers generated by that same example; the macros accept only their described simple arguments.
Use allocation and ownership, cleanup, and macro limitations when adapting them. Passing these demonstrations does not establish a robust parser for arbitrary external files, an unbounded recursion policy, or a generally hygienic swap macro.
6. Thought check: output versus explanation
You predicted the sum correctly. What else should you explain before adapting the function?
State the input region/count and lifetime, destination validity, numeric domain and overflow proof, aliasing/mutation policy, rejection behavior, and thread assumptions. The output is one observation within that contract.
Sources and further reading
Before you move on
- A complete program joins several object, control-flow, and interface contracts.
- Success, rejection, and cleanup paths all contribute to the promised behavior.
- Boundary cases help test the reasoning without proving every possible execution.
Keep these ideas separate
- Observed output / Explained behavior
- An output is evidence for one case; an explanation connects it to types, state changes, bounds, and contracts.
Pick one complete example and explain what stays unchanged when it rejects invalid input.
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Its input assumptions, boundaries, failures, and resource handling.
✓ Correct reasoning. An observed output is one piece of evidence about a larger contract.
- Only whether its variable names match another example.
Names alone do not establish equivalent behavior.
- Nothing; one output proves every execution.
Different inputs and paths can exercise different conditions.
General
Quick reference from the earlier edition
Retained for existing section links and saved passages. Exact corrections are documented in the source review.
The following short, self-contained programs put the concepts above into practice.
Hello, World
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
return 0;
}
Variables and Arithmetic
#include <stdio.h>
int main(void) {
int a = 7, b = 3;
printf("Sum: %d, Product: %d, Quotient: %.2f\n",
a + b, a * b, (double)a / b);
return 0;
}
Control Flow
#include <stdio.h>
int main(void) {
for (int i = 1; i <= 20; i++) {
if (i % 15 == 0) printf("FizzBuzz\n");
else if (i % 3 == 0) printf("Fizz\n");
else if (i % 5 == 0) printf("Buzz\n");
else printf("%d\n", i);
}
return 0;
}
Recursion
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
/* Returns 0 for an invalid argument or a result too large for long.
This teaching example uses small n; very deep recursion can exhaust resources. */
long factorial(int n) {
if (n < 0) return 0;
if (n <= 1) return 1;
long partial = factorial(n - 1);
if (partial == 0 || partial > LONG_MAX / n) return 0;
return n * partial;
}
int main(void) {
long result = factorial(5);
if (result == 0) {
fputs("Invalid argument or factorial overflow\n", stderr);
return EXIT_FAILURE;
}
printf("5! = %ld\n", result);
return EXIT_SUCCESS;
}
Arrays and Pointer Arithmetic
#include <stdio.h>
int main(void) {
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; /* array decays to a pointer to arr[0] */
for (int i = 0; i < 5; i++) {
printf("%d ", *(p + i)); /* equivalent to arr[i] */
}
printf("\n");
return 0;
}
A Self-Referential Struct: Singly Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
int main(void) {
struct Node *head = malloc(sizeof *head);
struct Node *second = malloc(sizeof *second);
if (head == NULL || second == NULL) {
free(second);
free(head);
return EXIT_FAILURE;
}
head->data = 1;
head->next = second;
second->data = 2;
second->next = NULL;
for (struct Node *cur = head; cur != NULL; cur = cur->next) {
printf("%d -> ", cur->data);
}
printf("NULL\n");
free(second);
free(head);
return EXIT_SUCCESS;
}
A Dynamic Array That Grows with realloc
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t capacity = 2, count = 0;
int *nums = malloc(capacity * sizeof *nums);
if (nums == NULL) return EXIT_FAILURE;
for (int i = 0; i < 5; i++) {
if (count == capacity) {
if (capacity > SIZE_MAX / 2) {
free(nums);
return EXIT_FAILURE;
}
size_t new_capacity = capacity * 2;
if (new_capacity > SIZE_MAX / sizeof *nums) {
free(nums);
return EXIT_FAILURE;
}
int *tmp = realloc(nums, new_capacity * sizeof *nums);
if (tmp == NULL) {
free(nums);
return EXIT_FAILURE;
}
nums = tmp;
capacity = new_capacity;
}
nums[count++] = i * i; /* i is only 0 through 4 here */
}
for (size_t i = 0; i < count; i++) printf("%d ", nums[i]);
printf("\n");
free(nums);
return EXIT_SUCCESS;
}
Writing to and Reading from a File
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *out = fopen("numbers.txt", "w");
if (out == NULL) return EXIT_FAILURE;
for (int i = 1; i <= 3; i++) {
if (fprintf(out, "%d\n", i) < 0) {
fclose(out);
return EXIT_FAILURE;
}
}
if (fclose(out) == EOF) return EXIT_FAILURE;
FILE *in = fopen("numbers.txt", "r");
if (in == NULL) return EXIT_FAILURE;
int value;
int status;
while ((status = fscanf(in, "%d", &value)) == 1) {
if (printf("Read: %d\n", value) < 0) {
fclose(in);
return EXIT_FAILURE;
}
}
/* This file contains only the small integers written above. */
int failed = ferror(in) || status != EOF;
if (fclose(in) == EOF) failed = 1;
return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
Correctly Parenthesized Macros
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#define SWAP(T, a, b) do { T temp = (a); (a) = (b); (b) = temp; } while (0)
int main(void) {
int a = 4, b = 9;
printf("SQUARE(2+3) = %d\n", SQUARE(2 + 3)); /* correctly 25, not 11 */
SWAP(int, a, b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Macro limitations: These macros are examples for simple arguments, not general replacements for functions. SQUARE(i++) is still undefined; SWAP evaluates its arguments repeatedly and its internal name temp can collide with a caller name. Use simple, distinct modifiable lvalues for this SWAP, avoid side effects, and prefer typed functions where practical.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.