“Certified Zig Programming Expert” – Master the language of modern systems programming
Welcome back, young Zig programmer! In Module One, you learned what Zig is, how to install it, and how to write your first programs. You learned about variables, constants, data types, control flow, functions, structs, enums, arrays, slices, and strings. You have built a strong foundation.
Now it is time to learn something very important: memory management and error handling. Every computer has memory, which is like a giant warehouse where programs store their data. In some languages, the computer manages memory for you. In Zig, you are the boss of your memory. You decide when to use it and when to free it.
This might sound scary, but it is actually very powerful. It makes your programs fast and safe. Zig also has a wonderful way of handling errors using things called optionals and error unions. These help you write programs that do not crash.
In this module, we will learn about pointers, allocators, defer, errdefer, optionals, error unions, try, catch, comptime, and generics. By the end, you will write memory-safe Zig programs with proper error handling. Let's begin!
After finishing this module, you will be able to:
defer and errdefer to clean up resources.try and catch for error handling.comptime.Ngozi is 14 years old and lives in Enugu. She has been learning Zig with her older brother. One day, her brother said, “Ngozi, let me teach you about memory. Imagine your computer has a giant warehouse. Every time you create a variable, you take a box from the warehouse and put something inside.”
Ngozi understood. “So when I write var age: u8 = 13;, I am taking a small box and putting the number 13 in it?” she asked. “Exactly!” her brother said.
“But what happens if I take too many boxes and never return them?” Ngozi asked. “That is called a memory leak,” her brother said. “The warehouse runs out of boxes, and the computer slows down. In Zig, you must return the boxes when you are done.”
Ngozi learned about allocators, which are like warehouse managers. She learned about defer, which is a way of saying, “When I finish this task, please return the box.” She learned about try and catch, which help her handle problems gracefully.
By the end of the day, Ngozi had written a small program that used memory carefully. Nothing leaked, and nothing crashed. Her brother said, “You are becoming a real Zig programmer!”
Moral of the story: In Zig, you are the boss of memory. You decide when to take it and when to give it back. Zig's tools (allocators, defer, try, catch) help you do this safely.
Definition: Memory is the part of a computer where programs store data while they are running.
Why it is important: Without memory, programs cannot store or use data.
Simple explanation: Imagine a giant warehouse with many boxes. Each box holds a piece of data.
Real-life example: A bank stores customer balances in memory.
School example: A school stores student scores in memory.
Home example: A family stores a shopping list in memory.
Nigerian example: A trader stores the day’s sales in memory.
Illustration:
Memory = Giant Warehouse
+------+ +------+ +------+ +------+
| Box1 | | Box2 | | Box3 | | Box4 |
+------+ +------+ +------+ +------+
| | | |
age=13 name="Ada" score=90 price=500
Mini summary: Memory is where programs store data. It is like a warehouse full of boxes.
Definition: A pointer is a variable that holds the address of another variable in memory.
Why it is important: Pointers let you access and change data in memory directly.
Simple explanation: Imagine a box with a note inside that says, “Look in Box 5.” That is a pointer.
Real-life example: A bank uses pointers to find customer accounts quickly.
School example: A teacher uses pointers to find student records.
Home example: A family uses pointers to find items in storage.
Nigerian example: A trader uses pointers to find products in a warehouse.
Illustration:
Pointer Example:
var age: u8 = 13;
const ptr = &age; // ptr points to age
std.debug.print("{d}\n", .{ptr.*}); // prints 13
& = "address of"
.* = "value at"
Step-by-step:
& to get its address..* to get the value through the pointer.Mini summary: A pointer holds an address. Use & to get addresses and .* to get values.
Definition: An allocator is a tool that gives your program memory when it needs it.
Why it is important: Allocators manage memory carefully so your program does not waste it.
Simple explanation: Like a librarian who gives you books and takes them back when you are done.
Real-life example: Banks use allocators to handle many transactions.
School example: Schools use allocators for student data.
Home example: Families use allocators for shopping lists that grow.
Nigerian example: Businesses use allocators for growing sales data.
Illustration:
Allocator = Memory Manager
Program → Allocator → Memory
|
V
"Give me 100 bytes"
|
V
"Here you go" → Use → "Free it"
Mini summary: Allocators provide and manage memory. They are essential for growing data.
Definition: GeneralPurposeAllocator is Zig's general-purpose memory manager. It is safe and detects memory leaks.
Why it is important: It is the recommended allocator for most programs.
Simple explanation: Like a smart warehouse manager who tracks every box you take and reminds you to return it.
Real-life example: Banks use it to track all memory usage.
School example: Schools use it to avoid leaks.
Home example: Families use it to keep memory clean.
Nigerian example: Businesses use it for safe programs.
Illustration:
Using GeneralPurposeAllocator:
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const memory = try allocator.alloc(u8, 10);
defer allocator.free(memory);
Step-by-step:
GeneralPurposeAllocator.defer to clean it up..allocator().alloc to get memory.free to release it (often with defer).Mini summary: GeneralPurposeAllocator is the recommended allocator. It tracks memory and detects leaks.
Definition: ArenaAllocator is an allocator that frees all memory at once.
Why it is important: It is fast and simple for short-lived tasks.
Simple explanation: Like using a big box, then throwing the whole box away when done.
Real-life example: Banks use it for one-time tasks.
School example: Schools use it for one-time reports.
Home example: Families use it for one-time lists.
Nigerian example: Traders use it for daily summaries.
Illustration:
Using ArenaAllocator: var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); _ = try allocator.alloc(u8, 100); _ = try allocator.alloc(u8, 200); // All freed when arena.deinit() runs
Step-by-step:
ArenaAllocator.defer to free everything at the end.Mini summary: ArenaAllocator frees all memory at once. It is fast and simple.
Definition: defer runs code when a block ends. errdefer runs only when an error occurs.
Why it is important: They ensure cleanup always happens.
Simple explanation: Like setting an alarm to remind you to lock the door when you leave.
Real-life example: Banks use defer to close files.
School example: Schools use defer to close books.
Home example: Families use defer to turn off lights.
Nigerian example: Businesses use defer to release resources.
Illustration:
defer:
const file = try openFile("data.txt");
defer file.close(); // runs at end of block
errdefer:
const memory = try allocator.alloc(u8, 10);
errdefer allocator.free(memory); // runs if error
Step-by-step:
defer right after you take a resource.errdefer when you only want cleanup on errors.Mini summary: defer runs at block end. errdefer runs only on error. They ensure cleanup.
Definition: An optional is a value that might or might not exist. It is written as ?T.
Why it is important: Optionals let you handle missing values safely.
Simple explanation: Like a box that might be empty or might have something inside.
Real-life example: A bank looks up an account that might not exist.
School example: A teacher looks up a student who might not be enrolled.
Home example: A family looks up a phone number that might be missing.
Nigerian example: A trader looks up a price that might not be set.
Illustration:
Optional Example:
var maybe_age: ?u8 = null;
maybe_age = 13;
if (maybe_age) |age| {
std.debug.print("Age: {d}\n", .{age});
} else {
std.debug.print("No age given.\n", .{});
}
Step-by-step:
?T to declare an optional.null for empty.if (maybe) |value| to get the value.else for the missing case.Mini summary: Optionals are values that might be missing. Use ?T and handle both cases.
Definition: An error union is a value that is either a result or an error. It is written as !T.
Why it is important: Error unions let functions report problems cleanly.
Simple explanation: Like a package that might be delivered or might be lost.
Real-life example: A bank transfers money that might fail.
School example: A teacher grades a test that might have errors.
Home example: A family buys an item that might be out of stock.
Nigerian example: A trader sells an item that might be unavailable.
Illustration:
Error Union Example:
fn divide(a: i32, b: i32) !i32 {
if (b == 0) return error.DivideByZero;
return a / b;
}
const result = divide(10, 2) catch |err| {
std.debug.print("Error: {}\n", .{err});
return;
};
Step-by-step:
!T as the return type.error.Name.try or catch.Mini summary: Error unions report results or errors. Use !T and handle both cases.
Definition: try passes an error up. catch handles it here.
Why it is important: They make error handling clean and clear.
Simple explanation: Like passing a problem to your teacher (try) or solving it yourself (catch).
Real-life example: Banks use try to pass errors up.
School example: Schools use try in functions.
Home example: Families use catch to handle problems.
Nigerian example: Businesses use try in their code.
Illustration:
try:
fn doWork() !void {
const data = try readFile("data.txt");
std.debug.print("Got data: {s}\n", .{data});
}
catch:
const data = readFile("data.txt") catch |err| {
std.debug.print("Failed: {}\n", .{err});
return;
};
Step-by-step:
try to propagate errors up.catch to handle errors locally.catch |err| to get the error value.catch unreachable only if you are sure there is no error.Mini summary: try passes errors up; catch handles them. Use them to control errors.
Definition: comptime means code that runs while the program is being compiled, not while it is running.
Why it is important: comptime makes programs faster and safer.
Simple explanation: Like preparing ingredients before cooking, instead of during cooking.
Real-life example: Banks precompute interest tables.
School example: Schools precompute timetables.
Home example: Families prepare meals in advance.
Nigerian example: Traders prepare price lists in advance.
Illustration:
comptime Example:
const size = comptime 5 + 5; // computed at compile time
fn makeArray() [size]u8 {
return [_]u8{0} ** size;
}
Step-by-step:
comptime before a value or block.Mini summary: comptime runs at compile time. It makes programs faster and safer.
Definition: Generics are functions or types that work with many types.
Why it is important: Generics let you write code once and use it with many types.
Simple explanation: Like a single tool that fits many sizes.
Real-life example: Banks use generic functions for different account types.
School example: Schools use generic functions for different subjects.
Home example: Families use generic containers for different items.
Nigerian example: Traders use generic lists for different products.
Illustration:
Generic Function:
fn add(comptime T: type, a: T, b: T) T {
return a + b;
}
const x = add(i32, 3, 4); // 7
const y = add(f64, 3.5, 4.5); // 8.0
Step-by-step:
comptime T: type as a parameter.T in the rest of the function.Mini summary: Generics let you write one function for many types. Use comptime T: type.
Definition: Mistakes happen. Knowing them helps you avoid them.
Why it is important: Small mistakes can cause crashes or leaks.
Simple explanation: Like forgetting to close a door.
Real-life example: Banks avoid leaks in their software.
School example: Students learn from memory errors.
Home example: Families avoid wasting resources.
Nigerian example: Businesses fix memory bugs quickly.
Table of common mistakes:
| Mistake | What Happens | How to Fix |
|---|---|---|
Forgetting defer | Memory leak | Use defer right after allocation |
| Using freed memory | Crash | Never use after free |
| Not handling errors | Crash | Use try or catch |
Using unreachable wrongly | Crash | Use only when sure |
| Optional without check | Crash | Use if (maybe) |v| |
| Wrong allocator lifetime | Crash | Use correct scope |
Mini summary: Common mistakes: missing defer, using freed memory, ignoring errors. Fix them early.
Definition: Best practices are good habits that keep your code clean and safe.
Why it is important: Good habits prevent bugs and crashes.
Simple explanation: Like washing your hands before cooking.
Real-life example: Banks follow strict coding rules.
School example: Students follow coding guidelines.
Home example: Families keep resources organized.
Nigerian example: Businesses use consistent code style.
List of best practices:
defer immediately after allocation.GeneralPurposeAllocator for general use.ArenaAllocator for short-lived tasks.try to propagate; catch to handle.comptime for constants and sizes.Mini summary: Best practices: defer, free memory, handle errors, use optionals and error unions, test.
Let’s build a small program that uses memory safely.
Step 1: Create a GeneralPurposeAllocator.
Step 2: Use defer to free it.
Step 3: Allocate an array of numbers.
Step 4: Use defer to free the array.
Step 5: Fill the array with values.
Step 6: Print the values.
Step 7: Use an optional to check if values exist.
Step 8: Use error union in a helper function.
Illustration:
Safe Program Structure:
main()
|
V
GPA + defer deinit
|
V
alloc() + defer free
|
V
Fill data
|
V
Print data
|
V
Clean exit 🎉
Mini summary: A safe program uses allocators, defer, optionals, and error unions together.
You now have a powerful toolkit for memory and errors.
Your toolkit:
Illustration:
Your Toolkit: +----------+ +----------+ +----------+ | Pointers | | Allocs | | defer | +----------+ +----------+ +----------+ +----------+ +----------+ +----------+ | Optionals| | !T | | try/catch| +----------+ +----------+ +----------+ +----------+ +----------+ | comptime | | Generics | +----------+ +----------+
Mini summary: You now have a toolkit for memory and errors. Use it wisely.
| Word | Simple Definition |
|---|---|
| Memory | Where programs store data. |
| Pointer | A variable that holds an address. |
| Allocator | A tool that provides memory. |
| GeneralPurposeAllocator | A safe, general allocator. |
| ArenaAllocator | An allocator that frees all at once. |
| defer | Run code at block end. |
| errdefer | Run code only on error. |
| Optional | A value that might be missing (?T). |
| Error union | A result or error (!T). |
| try | Pass an error up. |
| catch | Handle an error here. |
| comptime | Code that runs at compile time. |
| Generic | Code that works with many types. |
| Memory leak | Memory that is never freed. |
| null | Empty optional value. |
& and .*.?T.!T.comptime T: type.GeneralPurposeAllocator.defer _ = gpa.deinit();.const allocator = gpa.allocator();.alloc to get memory.defer allocator.free(memory);.!T.error.Name.try to propagate errors.catch to handle them.catch |err| to get the error.?T.null for empty.if (maybe) |v| to unwrap.else for missing.comptime T: type as a parameter.T in the body.comptime before a value or block.defer to close files.defer for clean code.defer to clean up after snacks.try for risky steps.defer to turn off lights.defer runs in reverse order.comptime can compute complex values.try is a shortcut for catch |err| return err?defer cleans up at block end.errdefer cleans up on error.try passes; catch handles.comptime runs at compile time.defer.unreachable wrongly.defer right after allocation.try to propagate; catch to handle.
Memory = Warehouse
+------+ +------+ +------+ +------+
| Box1 | | Box2 | | Box3 | | Box4 |
+------+ +------+ +------+ +------+
| | | |
age=13 name="Ada" score=90 price=500
ptr → age (13) & = "address of" .* = "value at"
Program → Allocator → Memory Allocate → Use → Free
defer → runs at end of block errdefer → runs only on error
Optional: ?T = value or null Error union: !T = value or error
Module 1: Zig Basics
|
V
Module 2: Memory & Errors
|
V
Module 3: Advanced Features
|
V
Module 4: Real Projects
|
V
Zig Expert 🎉
| Feature | GeneralPurposeAllocator | ArenaAllocator |
|---|---|---|
| Frees memory | One at a time | All at once |
| Speed | Moderate | Very fast |
| Best for | Long-running code | Short-lived tasks |
| Leak detection | Yes | No |
| Feature | Optional (?T) | Error Union (!T) |
|---|---|---|
| Meaning | Value or null | Value or error |
| Use for | Missing value | Possible failure |
| Handling | if (x) |v| | try / catch |
| Feature | defer | errdefer |
|---|---|---|
| Runs | Always | Only on error |
| Best for | Cleanup | Partial cleanup |
| Order | Reverse | Reverse |
| Feature | comptime | runtime |
|---|---|---|
| When | Compile time | Run time |
| Speed | Fast | Slower |
| Best for | Constants, sizes | Dynamic data |
Lesson 1: Memory is where programs store data.
Lesson 2: Pointers hold addresses of values.
Lesson 3: Allocators provide and manage memory.
Lesson 4: GeneralPurposeAllocator is safe and detects leaks.
Lesson 5: ArenaAllocator frees all memory at once.
Lesson 6: defer cleans up; errdefer cleans up on error.
Lesson 7: Optionals (?T) handle missing values.
Lesson 8: Error unions (!T) report results or errors.
Lesson 9: try passes errors; catch handles them.
Lesson 10: comptime runs at compile time.
Lesson 11: Generics work with many types.
Lesson 12: Common mistakes: missing defer, using freed memory.
Lesson 13: Best practices: defer, free memory, handle errors.
Lesson 14: Build a safe program with allocators and errors.
Lesson 15: Your toolkit includes pointers, allocators, optionals, errors, comptime, generics.
Congratulations! You have finished Module Two of the Certified Zig Programming Expert course. You learned what memory is and how to use pointers. You learned about allocators (GeneralPurposeAllocator and ArenaAllocator). You learned about defer and errdefer for cleanup. You learned about optionals and error unions. You learned to use try and catch. You learned the basics of comptime and generics. You learned common mistakes and best practices. Most importantly, you now know how to write memory-safe Zig programs with proper error handling. In the next module, you will learn about advanced features and the standard library. Keep practising, and you will become a Zig expert!
Match the term to its meaning.
| Term | Meaning |
|---|---|
| 1. Pointer | A. Runs at block end |
| 2. Allocator | B. Value or null |
| 3. defer | C. Holds an address |
| 4. Optional | D. Provides memory |
| 5. Error union | E. Value or error |
Answers: 1-C, 2-D, 3-A, 4-B, 5-E
& operator.alloc(u8, N).defer.!T (error union).?T (optional).Title: “Write a Safe Memory Program Together”
Instructions: In groups of 3–4, write a Zig program that uses an allocator to create an array, fills it with numbers, prints them, and frees the memory. Add a function that returns an error union, and handle the error with try/catch. One person writes, one person tests, one person fixes, and one person presents. Share your program with the class.
Goal: Practice using allocators, defer, and error handling.
Task: Write a Zig program that:
GeneralPurposeAllocator.u8 values.defer to free memory.try in a helper function.Hint: Start with a small program and add features one at a time.
Project: “Safe Memory Manager”
Write a Zig program that:
GeneralPurposeAllocator.defer to deinitialize the allocator.defer to free the string.Example output:
Message: Hello, Zig! Length: 11 All done safely 🎉
Assignment: Write a Zig program that acts as a small inventory system. The program should:
ArenaAllocator.try and catch.defer.Submit: Your .zig file and a screenshot of the output.
defer cleans up at block end.errdefer cleans up on error.try passes; catch handles.comptime runs at compile time.defer useful?errdefer?comptime do, and why does it matter?In Module Three, we will learn about advanced features and the standard library. We will cover:
To prepare, make sure you have completed the practical assignment and have your Zig environment ready. Review the key vocabulary. Think about how you would build larger programs. Bring your curiosity!
See you in Module Three!
End of Module Two – Certified Zig Programming Expert