C from scratch
Bytes, addresses, pointers and the heap — then recursion, function pointers and threads, each with the bug a real compiler or a real crash would teach.
C hides almost nothing. A variable is a few bytes at an address, a pointer is an address you can store, and memory you ask for stays yours until you give it back. That makes C the clearest place to learn how a program actually sits in memory — and the easiest place to get it wrong.
This course walks through the programs in the repository one at a time. Each lesson shows what happens to the bytes, and each ends by compiling and running the code. That turned up several instructive problems: a missing header that newer compilers refuse, an integer overflow from 13! onward, a hand-typed π that limits a numerical integral, and a threaded matrix multiply that crashes before its first thread starts.
Prerequisites
None beyond comfort with a terminal. The final lesson assumes you know what a matrix product is.
Running the code
Every program is a single file:
cd c_from_scratch
gcc -Wall -Wextra -o factorial factorial.c
./factorial
Compile with -Wall -Wextra every time: three of the bugs below are reported as warnings that a plain gcc build hides. integral.c needs -lm for the maths library, and multi-threaded-mat-mul.c needs -lpthread.
Lessons
- 1 Variables, addresses and bytesA variable is a few bytes at an address. A string is bytes ending in zero. malloc hands you bytes that are yours until you free them.
- 2 Pointers and structsC passes everything by value. To let a function change your data, you pass the value of its address.
- 3 The heap - malloc, calloc and freeAsking for memory at run time, what it contains when you get it, and the checks that keep heap code from crashing.
- 4 Recursion and the call stackEvery call gets its own stack frame. Watch factorial build a tower of them, then find the two inputs that break it.
- 5 Function pointers and numerical integrationPassing a function to a function, the trapezoidal rule it powers, and how a hand-typed π quietly caps the accuracy.
- 6 Threads with pthreadsSplitting a matrix multiply across CPU threads — why one thread per element crashes, and how a handful of threads with a block of rows each gets a real speedup.