Explain it simply
Explain it simply
You have met a lot of C: variables and types, operators, branches and loops, arrays and strings, functions and recursion, input, files, addresses and pointers, malloc and free, structs, unions and enums. This lesson ties them together instead of adding anything new.
Picture the course as a toolbox. Each lesson handed you one tool. A real job, like keeping a list of daily expenses and saving it to disk, needs several tools at once, and the skill is knowing which to pick and how they fit together. The capstone example below is that job, and every line in it uses something you already know.
Problem → Why → Solution
The problem: it worked once, on my machine
C will happily compile a program that is wrong. Reading one element past an array, using memory after free, overflowing a signed int, not checking whether fopen succeeded: each of these can print the right answer today and crash tomorrow, or only on another computer, or only with optimisation turned on. The C standard calls these situations undefined behaviour, and it places no requirement at all on what happens next.
So a correct-looking run proves very little. The habits this course has been building, such as bounds checks, return-value checks, a clear owner for every malloc and warnings turned on, are what separate a program that happens to work from one that is correct.
Why one good run is not proof
Undefined behaviour is not a specific error; it is the absence of any rule. The compiler may assume it never happens and optimise accordingly, so the symptoms can move, vanish or appear far from the real mistake. Only checks in the code, plus tools such as -Wall -Wextra and sanitizers, make these bugs visible.
Core concept: the rules that run through every C program
Looking back, almost every lesson taught one of a handful of rules. Syntax is the easy part; these rules are what experienced C programmers think about on every line.
| Idea | The rule to remember |
|---|---|
| Types and integers | int / int truncates and signed overflow is undefined, so keep money in whole cents |
| Arrays and strings | An array does not know its length: pass a size with every pointer and leave room for '\0' |
| Pointers | A pointer is valid only while the object it points to is alive; NULL means "no object" |
| Dynamic memory | Every malloc or realloc needs exactly one free, by a clearly named owner |
| Errors | malloc, realloc, fopen, scanf and fprintf can all fail, so check what they return |
| Build | Compile with -Wall -Wextra and fix the warnings; on Linux or macOS add -fsanitize=address,undefined while testing |
The compilation model belongs on that list too. The preprocessor pastes in #include files and expands #define, the compiler turns each .c file into an object file, and the linker joins those object files with the C library. A missing prototype is a compiler problem; an "undefined reference" is a linker problem. Knowing which stage produced an error tells you where to look.
Object lifetime ties these rules together. A local variable lives until its block ends, a static or global one lives for the whole program, and a malloc'd block lives until someone calls free. Most serious C bugs are one of two shapes: a pointer outliving its object (use after free, returning a local's address) or an object outliving every pointer to it (a leak).
The language itself keeps evolving. C23 is the newest edition of the standard, while many projects still compile as C11 or C17, which is also what this course's examples are checked with. The rules above hold in every one of them.
- Create: declare or allocate the object
- Use it through checked pointers
- Check every call that can fail
- Release it exactly once, on one path
Ask of every pointer: which object does it point to, and is that object still alive?
General pattern: one cleanup label
int run(void) {
int status = 1; /* assume failure */
FILE *f = NULL;
struct Thing *t = malloc(sizeof *t);
if (t == NULL || (f = fopen("out.txt", "w")) == NULL) goto cleanup;
/* ... work; any failure jumps to cleanup ... */
status = 0; /* reached only on success */
cleanup:
if (f != NULL) fclose(f);
free(t); /* free(NULL) does nothing */
return status;
}Start every resource as NULL, record the result as failure, and jump to one label when anything goes wrong. The cleanup block releases whatever was acquired, which is safe because fclose is guarded and free(NULL) does nothing.
Capstone: an expense list that survives a save and load
The program records three expenses in a growing heap array, writes them to a temporary file as text, reads that file into a second list, and checks that both totals agree. Money is stored as whole cents in a long, so 12.50 is 1250 and no rounding error can creep in. tmpfile() provides a scratch file that is deleted automatically when it is closed, so nothing is left on disk. Here is which topic each part reuses:
- Structs: Expense groups an item with its price; ExpenseList keeps the array together with its count and capacity
- Pointers: every function takes the list by pointer, and by const pointer when it only reads
- Dynamic memory: realloc grows the array and list_free releases it
- Files: save_list writes one line per expense, and load_list parses them back with fgets and sscanf
- Strings: snprintf copies the item name and formats money without overflowing a buffer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Expense {
char item[24];
long cents; /* whole cents: integer maths never rounds */
};
struct ExpenseList {
struct Expense *data; /* heap array owned by the list */
size_t count;
size_t capacity;
};
/* Returns 0 on success, -1 if memory ran out (the list is left unchanged). */
int list_add(struct ExpenseList *list, const char *item, long cents) {
if (list->count == list->capacity) {
size_t cap = list->capacity == 0 ? 2 : list->capacity * 2;
struct Expense *bigger = realloc(list->data, cap * sizeof *bigger);
if (bigger == NULL) {
return -1;
}
list->data = bigger;
list->capacity = cap;
}
struct Expense *e = &list->data[list->count];
snprintf(e->item, sizeof e->item, "%s", item);
e->cents = cents;
list->count++;
return 0;
}
long list_total(const struct ExpenseList *list) {
long sum = 0;
for (size_t i = 0; i < list->count; i++) {
sum += list->data[i].cents;
}
return sum;
}
void list_free(struct ExpenseList *list) {
free(list->data);
list->data = NULL;
list->count = list->capacity = 0;
}
/* One "item;cents" line per expense. */
int save_list(FILE *f, const struct ExpenseList *list) {
for (size_t i = 0; i < list->count; i++) {
if (fprintf(f, "%s;%ld\n", list->data[i].item, list->data[i].cents) < 0) {
return -1;
}
}
return 0;
}
int load_list(FILE *f, struct ExpenseList *list) {
char line[64], item[24];
long cents;
while (fgets(line, sizeof line, f) != NULL) {
if (sscanf(line, "%23[^;];%ld", item, ¢s) != 2) {
return -1;
}
if (list_add(list, item, cents) != 0) {
return -1;
}
}
return 0;
}
/* Writes "12.50" into buf; the caller says how big buf is. */
void format_money(long cents, char *buf, size_t size) {
snprintf(buf, size, "%ld.%02ld", cents / 100, cents % 100);
}
int main(void) {
int status = 1;
FILE *f = NULL;
struct ExpenseList today = {NULL, 0, 0};
struct ExpenseList loaded = {NULL, 0, 0};
char money[32];
if (list_add(&today, "rice", 1250) != 0 || list_add(&today, "bus fare", 300) != 0 ||
list_add(&today, "notebook", 2725) != 0) {
goto cleanup;
}
f = tmpfile();
if (f == NULL || save_list(f, &today) != 0) {
goto cleanup;
}
printf("Saved %zu expenses\n", today.count);
rewind(f);
if (load_list(f, &loaded) != 0) {
goto cleanup;
}
printf("Loaded %zu expenses back:\n", loaded.count);
for (size_t i = 0; i < loaded.count; i++) {
format_money(loaded.data[i].cents, money, sizeof money);
printf(" %-10s %8s\n", loaded.data[i].item, money);
}
format_money(list_total(&loaded), money, sizeof money);
printf("Total: %s\n", money);
printf("Round trip matches: %s\n",
list_total(&loaded) == list_total(&today) ? "yes" : "no");
status = 0;
cleanup: /* one exit path releases everything */
if (f != NULL) {
fclose(f);
}
list_free(&today);
list_free(&loaded);
return status;
}Code breakdown
- Grow safely with realloc
struct Expense *bigger = realloc(list->data, cap * sizeof *bigger);The result goes into a new pointer first. If realloc fails it returns NULL, but the old block is still valid and still owned by list->data, so nothing leaks. Writing list->data = realloc(list->data, ...) would overwrite the only pointer to that block.
- Bounded string copy
snprintf(e->item, sizeof e->item, "%s", item);snprintf never writes more than sizeof e->item bytes and always ends the string with '\0', so a long name is cut short instead of overflowing the struct. strcpy has no size and would write past the 24 bytes.
- Parse what you saved
if (sscanf(line, "%23[^;];%ld", item, ¢s) != 2) {%23[^;] reads up to 23 characters that are not a semicolon, which lets item names contain spaces, as in "bus fare". Any line that does not yield both fields makes load_list fail instead of loading half a record.
- Money from cents
snprintf(buf, size, "%ld.%02ld", cents / 100, cents % 100);Integer division gives the whole units and % gives the cents, while %02ld pads 0 to "00". The function takes buf together with its size, the same pointer-plus-length pairing you used for arrays. It is designed for non-negative amounts only.
- Back to the start of the file
rewind(f);After writing, the file position is at the end. rewind moves it back to the start so load_list reads what save_list wrote. The C standard also requires a call such as rewind, fseek or fflush between writing and then reading the same stream.
- One exit for every outcome
cleanup:Every failure jumps here with status still 1; success arrives with status 0. Both lists are freed and the file is closed exactly once, whichever path was taken. Calling list_free on an empty list is safe because free(NULL) does nothing.
Saved 3 expenses
Loaded 3 expenses back:
rice 12.50
bus fare 3.00
notebook 27.25
Total: 42.75
Round trip matches: yesWhere to go after this course
You now have the core language. These are the skills that turn it into real-world C, listed roughly in the order they pay off:
- Split code into several .c files with .h headers, and build them with make or CMake
- Step through a running program with a debugger such as gdb, lldb or the one in your editor
- On Linux or macOS, run tests with -fsanitize=address,undefined to catch out-of-bounds access, use after free and overflow
- Build classic data structures yourself: a linked list, a hash table, a dynamic string
- Read the man pages or cppreference for each library function's return values and error cases
Read the first error, not the last
When the compiler prints twenty messages, fix the first one and compile again. A single missing semicolon or brace often causes all the others, and they disappear together. The messages can sound blunt, but the file name, line number and wording usually point straight at the problem.
In real projects
In real projects
The shape of this capstone, a struct that owns a heap array plus functions to add, save, load and free, is how a lot of production C is written. Projects such as SQLite, Redis and the Linux kernel are written in C and lean on small structs with init, add and free functions, careful length fields and error codes rather than exceptions. The goto cleanup pattern in main() appears all over the Linux kernel for the same reason it is used here: one exit path that releases everything.
Before C code ships, teams usually put it through more than one check: a warning-clean build with -Wall -Wextra (often with -Werror in CI), unit tests for each function, sanitizer runs that turn silent memory errors into loud reports, and fuzzing for anything that parses outside input. Each one catches bugs the others miss.
Common mistakes
Common mistakes
Overwriting the only pointer with realloc's result
list->data = realloc(list->data, n) looks tidy, but if realloc returns NULL the old block is still allocated and you have just lost its address: a leak, plus a NULL data pointer that the next line will dereference. Assign to a temporary and copy it over only after the check.
Treating a float as money
0.1 + 0.2 is not exactly 0.3 in binary floating point, so totals drift by a cent once enough values are added and compared. Store whole cents in an integer type and convert only when printing.
Forgetting to rewind or close a file
Switching from writing to reading on the same stream without rewind or fseek is undefined by the C standard, and even where it seems to work the position is at the end of the file, so there is nothing left to read. Forgetting fclose can lose data that fprintf is still holding in a buffer, and it leaks the file handle.
Freeing twice on different paths
When each error branch calls free and the end of the function frees again, some path eventually frees the same block twice, which is undefined behaviour. A single cleanup label, plus setting pointers to NULL after free, makes double frees much harder to write.
Mini challenge
Capstone challenge: count the words in a file
Write a word-frequency counter that pulls the whole course together: read words from a file, count each one in a struct array that grows with realloc, and report the most frequent word. Test it with a sentence and with an empty file.
- struct WordCount holds a word (up to 31 characters) and its count
- find_word() returns a pointer to an existing entry, or NULL
- add_word() bumps an existing word or appends a new one, growing a full array first
- Words are lower-cased with tolower before counting, so "The" and "the" match
- Both the array and the file are released on every path, including the empty file
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct WordCount {
char word[32];
int count;
};
struct WordList {
struct WordCount *items;
size_t count;
size_t capacity;
};
struct WordCount *find_word(struct WordList *list, const char *word) {
// TODO: linear search with strcmp; NULL when the word is absent
}
int add_word(struct WordList *list, const char *word) {
// TODO: bump an existing count, or grow with realloc and append
// TODO: return -1 if memory runs out, 0 otherwise
}
int count_words(FILE *f, struct WordList *list) {
// TODO: read with fscanf(f, "%31s", ...), lower-case each word, add it
}
void report(const struct WordList *list) {
// TODO: "No words" when empty; else word=count pairs, then the top word
}
int main(void) {
// TODO: for "The cat and the dog and THE bird\n" and for "":
// tmpfile(), fputs the text, rewind, count, report, free, fclose
}Expected: For the sentence: the=3 cat=1 and=2 dog=1 bird=1, then "Most frequent: the (3)". For the empty file: "No words". Every allocation is freed in both runs.
Show hint
fscanf with %31s skips whitespace and stops at the next space, so each call yields one word and never more than 31 characters. Pass each character through tolower((unsigned char)c). For the empty file, count_words simply adds nothing, and report must check list->count before touching items[0].
Show solution
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct WordCount {
char word[32];
int count;
};
struct WordList {
struct WordCount *items;
size_t count;
size_t capacity;
};
struct WordCount *find_word(struct WordList *list, const char *word) {
for (size_t i = 0; i < list->count; i++) {
if (strcmp(list->items[i].word, word) == 0) {
return &list->items[i];
}
}
return NULL;
}
/* Counts one more use of word. Returns 0 on success, -1 if out of memory. */
int add_word(struct WordList *list, const char *word) {
struct WordCount *found = find_word(list, word);
if (found != NULL) {
found->count++;
return 0;
}
if (list->count == list->capacity) {
size_t cap = list->capacity == 0 ? 4 : list->capacity * 2;
struct WordCount *bigger = realloc(list->items, cap * sizeof *bigger);
if (bigger == NULL) {
return -1;
}
list->items = bigger;
list->capacity = cap;
}
struct WordCount *slot = &list->items[list->count++];
snprintf(slot->word, sizeof slot->word, "%s", word);
slot->count = 1;
return 0;
}
/* Reads every word from f into list, lower-cased. 0 = ok, -1 = no memory. */
int count_words(FILE *f, struct WordList *list) {
char word[32];
while (fscanf(f, "%31s", word) == 1) {
for (char *p = word; *p != '\0'; p++) {
*p = (char)tolower((unsigned char)*p);
}
if (add_word(list, word) != 0) {
return -1;
}
}
return 0;
}
void report(const struct WordList *list) {
if (list->count == 0) {
printf("No words\n");
return;
}
const struct WordCount *top = &list->items[0];
for (size_t i = 0; i < list->count; i++) {
const struct WordCount *w = &list->items[i];
printf("%s%s=%d", i == 0 ? "" : " ", w->word, w->count);
if (w->count > top->count) {
top = w;
}
}
printf("\nMost frequent: %s (%d)\n", top->word, top->count);
}
int run(const char *text) {
FILE *f = tmpfile();
if (f == NULL) {
return -1;
}
fputs(text, f);
rewind(f);
struct WordList list = {NULL, 0, 0};
int status = count_words(f, &list);
if (status == 0) {
report(&list);
}
free(list.items);
fclose(f);
return status;
}
int main(void) {
if (run("The cat and the dog and THE bird\n") != 0 || run("") != 0) {
printf("Something failed\n");
return 1;
}
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Most C rules come back to lifetime, bounds, integer behaviour and ownership
- Give every malloc one owner and one free, and realloc into a temporary pointer
- Check every call that can fail, and release resources on a single cleanup path
- Store money in integer cents and pass every buffer together with its size
- Next: multi-file builds, a debugger, sanitizers and your own data structures
ISO C Working Group (WG14) — ISO/IEC JTC1/SC22/WG14