Systems from Scratch
This section teaches systems programming from zero, with Zig instead of C. Each chapter asks one question and answers the question in plain terms. Then the chapter gives you a complete program that proves the answer. If you know C, the last part of each page shows how to write the same idea in C. If you do not know C, you do not need it here. The chapters follow the order of a C course, and no earlier part of the guide is necessary, so you can read this section at any time, also first.
- A type is not a property of the bytes. A type is an agreement about how to read the bytes. You can read the same four bytes in two ways, with no conversion.
u8andu32are not two styles for one number. The two types use different amounts of memory. For a million values, the difference is three million bytes.- An address is an ordinary number.
@intFromPtrdoes no work. It shows you the number that the pointer already contained. - When a function returns, the memory of its local variables becomes free, and the next call gets the same bytes. The reuse of those bytes makes a dangling pointer. The pointer itself did not change.
- Undefined behaviour is not a crash and not a garbage value. Undefined behaviour is a promise that you made to the compiler. If you break that promise, code in a different part of the program can change.
11 chapters.
- Everything Is BytesA type is not a property of the bytes. A type is an agreement about how to read the bytes.
- Numbers Have a SizeA u8 counts to 255 and stops. You decide what happens next.
- Memory Is NumberedAn address is an ordinary number, and a pointer is a variable that holds an address.
- The StackWhere local variables live, and why a pointer to a local is not safe after the call returns.
- Who Owns This MemoryMemory that must stay valid after a call returns needs a request, and a person or a function must give it back.
- Off the EndA length is a value. Languages are different in who must check the length.
- When the Checks Are OffWhat undefined behaviour is, and what each build mode promises.
- Strings Are BytesZig has no string type. A literal is bytes, with a zero at the end.
- Structs Are LayoutFields are next to each other in memory, and the size is not the sum of the parts.
- Errors Are ValuesZig has no exception mechanism below your program. Thus a failure must be part of the value that a function returns.
- Talk to the Operating SystemYour program gets streams that it did not open, and it must return a status.