Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Certified Zig Programming Expert · Lesson 3 of 5

Module Two

📖 Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
3
Certified Zig Programming Expert – Module Two

Module Two: Memory Management and Error Handling – Being the Boss of Your Computer's Memory

“Certified Zig Programming Expert” – Master the language of modern systems programming

Module Introduction

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!

Learning Objectives

After finishing this module, you will be able to:

  • Explain what memory is and why it matters.
  • Understand pointers and how to use them.
  • Use Zig's allocators to manage memory.
  • Use defer and errdefer to clean up resources.
  • Explain what optionals (?T) are.
  • Explain what error unions (!T) are.
  • Use try and catch for error handling.
  • Understand the basics of comptime.
  • Write simple generic functions.
  • Complete a mini project and practical assignment.

Warm-up Story: Ngozi’s Memory Warehouse

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.

Main Lessons

Lesson 1: What is Memory?

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.

Lesson 2: What is a Pointer?

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:

  1. Create a variable.
  2. Use & to get its address.
  3. Store the address in a pointer.
  4. Use .* to get the value through the pointer.

Mini summary: A pointer holds an address. Use & to get addresses and .* to get values.

Lesson 3: What is an Allocator?

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.

Lesson 4: GeneralPurposeAllocator

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:

  1. Create a GeneralPurposeAllocator.
  2. Use defer to clean it up.
  3. Get the allocator with .allocator().
  4. Use alloc to get memory.
  5. Use free to release it (often with defer).

Mini summary: GeneralPurposeAllocator is the recommended allocator. It tracks memory and detects leaks.

Lesson 5: ArenaAllocator

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:

  1. Create an ArenaAllocator.
  2. Use defer to free everything at the end.
  3. Get the allocator.
  4. Use memory freely.
  5. All memory is freed at once when the arena is deinitialized.

Mini summary: ArenaAllocator frees all memory at once. It is fast and simple.

Lesson 6: defer and errdefer

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:

  1. Use defer right after you take a resource.
  2. Use errdefer when you only want cleanup on errors.
  3. They run when the function or block ends.
  4. They run in reverse order (last one first).

Mini summary: defer runs at block end. errdefer runs only on error. They ensure cleanup.

Lesson 7: Optionals (?T)

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:

  1. Use ?T to declare an optional.
  2. Set it to null for empty.
  3. Use if (maybe) |value| to get the value.
  4. Use else for the missing case.

Mini summary: Optionals are values that might be missing. Use ?T and handle both cases.

Lesson 8: Error Unions (!T)

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:

  1. Use !T as the return type.
  2. Return errors with error.Name.
  3. Handle them with try or catch.

Mini summary: Error unions report results or errors. Use !T and handle both cases.

Lesson 9: try and catch

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:

  1. Use try to propagate errors up.
  2. Use catch to handle errors locally.
  3. Use catch |err| to get the error value.
  4. Use 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.

Lesson 10: Introduction to comptime

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:

  1. Use comptime before a value or block.
  2. The compiler computes it.
  3. Use it for sizes, constants, and types.

Mini summary: comptime runs at compile time. It makes programs faster and safer.

Lesson 11: Generics in Zig

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:

  1. Use comptime T: type as a parameter.
  2. Use T in the rest of the function.
  3. Call with a specific type.

Mini summary: Generics let you write one function for many types. Use comptime T: type.

Lesson 12: Common Mistakes in Memory and Errors

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:

MistakeWhat HappensHow to Fix
Forgetting deferMemory leakUse defer right after allocation
Using freed memoryCrashNever use after free
Not handling errorsCrashUse try or catch
Using unreachable wronglyCrashUse only when sure
Optional without checkCrashUse if (maybe) |v|
Wrong allocator lifetimeCrashUse correct scope

Mini summary: Common mistakes: missing defer, using freed memory, ignoring errors. Fix them early.

Lesson 13: Best Practices for Memory and Errors

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:

  • Use defer immediately after allocation.
  • Always free what you allocate.
  • Use GeneralPurposeAllocator for general use.
  • Use ArenaAllocator for short-lived tasks.
  • Handle every error.
  • Use optionals for values that might be missing.
  • Use error unions for functions that can fail.
  • Use try to propagate; catch to handle.
  • Use comptime for constants and sizes.
  • Write tests for your code.

Mini summary: Best practices: defer, free memory, handle errors, use optionals and error unions, test.

Lesson 14: Building a Safe Zig Program

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.

Lesson 15: Putting It All Together – Your Memory Toolkit

You now have a powerful toolkit for memory and errors.

Your toolkit:

  • Pointers: Address of values.
  • Allocators: GeneralPurpose, Arena.
  • defer/errdefer: Cleanup on exit or error.
  • Optionals: Values that might be missing.
  • Error unions: Results or errors.
  • try/catch: Passing or handling errors.
  • comptime: Compile-time code.
  • Generics: Code for many types.

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.

Key Vocabulary

WordSimple Definition
MemoryWhere programs store data.
PointerA variable that holds an address.
AllocatorA tool that provides memory.
GeneralPurposeAllocatorA safe, general allocator.
ArenaAllocatorAn allocator that frees all at once.
deferRun code at block end.
errdeferRun code only on error.
OptionalA value that might be missing (?T).
Error unionA result or error (!T).
tryPass an error up.
catchHandle an error here.
comptimeCode that runs at compile time.
GenericCode that works with many types.
Memory leakMemory that is never freed.
nullEmpty optional value.

Important Concepts

  • Memory is a warehouse: Programs store data there.
  • Pointers hold addresses: Use & and .*.
  • Allocators manage memory: Use GPA or Arena.
  • defer ensures cleanup: Always runs at block end.
  • errdefer runs on error: Useful for partial cleanup.
  • Optionals handle missing values: Use ?T.
  • Error unions report problems: Use !T.
  • try and catch control errors: Pass or handle.
  • comptime makes code fast: Runs at compile time.
  • Generics work with many types: Use comptime T: type.

Step-by-step Explanations

How to use an allocator step by step

  1. Create a GeneralPurposeAllocator.
  2. Use defer _ = gpa.deinit();.
  3. Get the allocator: const allocator = gpa.allocator();.
  4. Use alloc to get memory.
  5. Use defer allocator.free(memory);.
  6. Use the memory.

How to handle an error step by step

  1. Make a function return !T.
  2. Return errors with error.Name.
  3. Use try to propagate errors.
  4. Use catch to handle them.
  5. Use catch |err| to get the error.

How to use optionals step by step

  1. Declare with ?T.
  2. Set to null for empty.
  3. Use if (maybe) |v| to unwrap.
  4. Use else for missing.

How to write a generic function step by step

  1. Use comptime T: type as a parameter.
  2. Use T in the body.
  3. Call with a specific type.

How to use comptime step by step

  1. Put comptime before a value or block.
  2. The compiler computes it.
  3. Use for sizes, constants, and types.

Real-life Examples

  • Banks: Use allocators for transactions.
  • Games: Use defer to close files.
  • Schools: Use optionals for optional data.
  • Homes: Use error unions for chores.
  • Businesses: Use comptime for constants.

Nigerian Examples

  • Banks: Nigerian banks use allocators for memory safety.
  • Startups: Startups use defer for clean code.
  • Schools: Students learn error handling early.
  • Businesses: Businesses use comptime for speed.
  • Freelancers: Freelancers use generics for reusable code.

Fun Examples Children Can Relate To

  • Games: Track scores with optionals.
  • Toys: Store toy lists with arrays.
  • Pets: Handle "pet not found" with error unions.
  • Snacks: Use defer to clean up after snacks.
  • Stories: Use generics to tell stories for any character.

Everyday Examples

  • Shopping: Handle missing prices with optionals.
  • Homework: Use try for risky steps.
  • Family: Use defer to turn off lights.
  • Time: Use comptime for fixed schedules.
  • Money: Use error unions for payments.

Parent Tips

  • Explain memory as a warehouse with boxes.
  • Teach your child to clean up after using resources.
  • Encourage them to read error messages.
  • Show them how banks use memory safely.
  • Praise them for writing safe code.
  • Practice with small programs.
  • Read Zig documentation together.
  • Keep sessions short and fun.
  • Let them teach you what they learned.
  • Support their learning journey.

Interesting Facts

  • Zig does not have a garbage collector.
  • Zig's defer runs in reverse order.
  • comptime can compute complex values.
  • Zig errors are values, not exceptions.
  • Zig supports C-style pointers.
  • Zig's allocators can be swapped easily.
  • Zig code can be faster than C.
  • Zig is used in production systems.

Did You Know?

  • Did you know that Zig can detect memory leaks?
  • Did you know that ArenaAllocator is fast?
  • Did you know that try is a shortcut for catch |err| return err?
  • Did you know that optionals replace null pointers?
  • Did you know that comptime can generate code?
  • Did you know that Zig generics are compile-time?
  • Did you know that Zig errors are checked at compile time?
  • Did you know that Nigerian developers use Zig for performance?

Remember This

  • Memory is where programs store data.
  • Pointers hold addresses.
  • Allocators provide memory.
  • Use GPA for general and Arena for short tasks.
  • defer cleans up at block end.
  • errdefer cleans up on error.
  • Optionals handle missing values.
  • Error unions report problems.
  • try passes; catch handles.
  • comptime runs at compile time.

Common Mistakes

  • Forgetting defer.
  • Using freed memory.
  • Not handling errors.
  • Using unreachable wrongly.
  • Optional without check.
  • Wrong allocator lifetime.
  • Ignoring compiler warnings.
  • Not testing code.

Best Practices

  • Use defer right after allocation.
  • Always free what you allocate.
  • Use GPA for general use.
  • Use Arena for short-lived tasks.
  • Handle every error.
  • Use optionals for missing values.
  • Use error unions for functions that can fail.
  • Use try to propagate; catch to handle.
  • Use comptime for constants and sizes.
  • Write tests.

Illustrations and Diagrams

Memory Diagram

  Memory = Warehouse

  +------+  +------+  +------+  +------+
  | Box1 |  | Box2 |  | Box3 |  | Box4 |
  +------+  +------+  +------+  +------+
     |        |         |         |
   age=13   name="Ada"  score=90  price=500
  

Pointer Diagram

  ptr → age (13)

  &  = "address of"
  .* = "value at"
  

Allocator Flow

  Program → Allocator → Memory

  Allocate → Use → Free
  

defer and errdefer

  defer → runs at end of block
  errdefer → runs only on error
  

Optional and Error Union

  Optional: ?T = value or null
  Error union: !T = value or error
  

Your Learning Journey

  Module 1: Zig Basics
        |
        V
  Module 2: Memory & Errors
        |
        V
  Module 3: Advanced Features
        |
        V
  Module 4: Real Projects
        |
        V
  Zig Expert 🎉
  

Comparison Tables

GPA vs Arena

FeatureGeneralPurposeAllocatorArenaAllocator
Frees memoryOne at a timeAll at once
SpeedModerateVery fast
Best forLong-running codeShort-lived tasks
Leak detectionYesNo

Optional vs Error Union

FeatureOptional (?T)Error Union (!T)
MeaningValue or nullValue or error
Use forMissing valuePossible failure
Handlingif (x) |v|try / catch

defer vs errdefer

Featuredefererrdefer
RunsAlwaysOnly on error
Best forCleanupPartial cleanup
OrderReverseReverse

comptime vs runtime

Featurecomptimeruntime
WhenCompile timeRun time
SpeedFastSlower
Best forConstants, sizesDynamic data

Lesson Summaries

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.

End-of-Module Summary

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!

Frequently Asked Questions

  1. What is memory? Where programs store data while running.
  2. What is a pointer? A variable that holds an address.
  3. What is an allocator? A tool that provides memory.
  4. What is the difference between GPA and Arena? GPA frees one at a time; Arena frees all at once.
  5. What is defer? Code that runs at block end.
  6. What is errdefer? Code that runs only on error.
  7. What is an optional? A value that might be missing (?T).
  8. What is an error union? A result or error (!T).
  9. What is comptime? Code that runs at compile time.
  10. What is a generic? Code that works with many types.

Matching Exercises

Match the term to its meaning.

TermMeaning
1. PointerA. Runs at block end
2. AllocatorB. Value or null
3. deferC. Holds an address
4. OptionalD. Provides memory
5. Error unionE. Value or error

Answers: 1-C, 2-D, 3-A, 4-B, 5-E

Scenario-based Exercises

  1. Scenario: You want to get the address of a variable. What do you use?
    Answer: The & operator.
  2. Scenario: You want to allocate an array of numbers. What do you do?
    Answer: Use an allocator with alloc(u8, N).
  3. Scenario: You want to clean up memory when a block ends. What do you use?
    Answer: defer.
  4. Scenario: Your function might fail. What return type do you use?
    Answer: !T (error union).
  5. Scenario: You want a value that might be missing. What do you use?
    Answer: ?T (optional).

Group Activity

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.

Individual Activity

Task: Write a Zig program that:

  • Uses a GeneralPurposeAllocator.
  • Allocates an array of 5 u8 values.
  • Fills them with numbers.
  • Prints them.
  • Uses defer to free memory.
  • Uses an optional to check if a value exists.
  • Uses try in a helper function.

Hint: Start with a small program and add features one at a time.

Mini Project

Project: “Safe Memory Manager”

Write a Zig program that:

  • Creates a GeneralPurposeAllocator.
  • Uses defer to deinitialize the allocator.
  • Allocates memory for a string.
  • Fills the string with "Hello, Zig!".
  • Uses defer to free the string.
  • Prints the string.
  • Uses an optional to store the string length.
  • Uses an error union in a helper function.

Example output:

  Message: Hello, Zig!
  Length: 11
  All done safely 🎉
  

Practical Assignment

Assignment: Write a Zig program that acts as a small inventory system. The program should:

  1. Use an ArenaAllocator.
  2. Create a struct for an item (name, price, quantity).
  3. Allocate an array of 5 items.
  4. Fill them with sample data.
  5. Calculate the total value.
  6. Use an optional to check if any item exists.
  7. Use an error union for a lookup function.
  8. Handle errors with try and catch.
  9. Free all memory with defer.
  10. Print a summary.

Submit: Your .zig file and a screenshot of the output.

Key Takeaways

  • Memory is where programs store data.
  • Pointers hold addresses.
  • Allocators provide memory.
  • Use GPA for general and Arena for short tasks.
  • defer cleans up at block end.
  • errdefer cleans up on error.
  • Optionals handle missing values.
  • Error unions report problems.
  • try passes; catch handles.
  • comptime runs at compile time.

Classroom Discussion Questions

  1. Why is memory important in programming?
  2. What is a pointer, and how do you use it?
  3. What is an allocator, and why does Zig use them?
  4. What is the difference between GPA and Arena?
  5. Why is defer useful?
  6. When would you use errdefer?
  7. What is an optional, and when do you use it?
  8. What is an error union, and why is it useful?
  9. What does comptime do, and why does it matter?
  10. What did Ngozi learn from her memory warehouse?

Preparation for Module Three

In Module Three, we will learn about advanced features and the standard library. We will cover:

  • Advanced comptime metaprogramming.
  • Generics and compile-time reflection.
  • Zig Build System (build.zig).
  • Unit testing and test blocks.
  • Zig Standard Library tour.
  • Interfacing with C (C ABI, @cImport).

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

🏆 Get Certified

🔒

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

🎓 Sign Up to Get Certified
🛠️ Practice Tools
Hands-on simulators & labs - subscription required.
→
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
→