CS210 · Block 2 · Lesson 15

Stack, Heap, malloc, free

Two memory regions · The malloc/free pattern · NULL checks · Ownership reasoning
At a glance: The last new content lesson before the midterm. You learn to ask the operating system for memory that lives past the function that asked, why every malloc needs a matching free, and how to reason about who owns each allocation. The memalloc walkthrough in Section 5 is where you practice; the lab puts it all to work building Spotify play counts.
Contents
  1. Lesson Objectives
  2. Assigned Readings
  3. Pre-Class Work
  4. Lesson Materials and Overview
  5. In-Class Work
  6. After Class
1. Lesson Objectives

By the end of this lesson, cadets will be able to:

  1. Distinguish memory allocated on the stack from memory allocated on the heap. (Outcome 2)
  2. Allocate and deallocate memory using malloc and free. (Outcome 2)
  3. Choose between stack and heap based on program requirements. (Outcomes 1, 3)
  4. Validate every allocation by checking for NULL. (Outcome 3)
  5. Reason about ownership: who allocates and who frees. (Outcomes 1, 3)
2. Assigned Readings

Complete before class. Beej Chapter 12 is the spine of today's lecture.

Source Sections Why
Beej-C Chapter 12 (Manual Memory Allocation) malloc, calloc, free, the NULL check pattern
King, C Programming: A Modern Approach Chapter 17 (Advanced Uses of Pointers) Optional deeper dive into heap allocation patterns
3. Pre-Class Work
Do this first
Plan on 30 to 45 minutes for the reading. The mechanics of malloc and free are small but the first time you write them feels strange; pre-class reading shortens the strangeness.

Pre-Class Checklist

1
Read Beej-C Chapter 12
Focus on these vocabulary items; we use them all day:
  • malloc, calloc, free, NULL
  • Stack vs heap
  • Initialization vs allocation (garbage vs zero)
  • Use after free and double free (preview for Lesson 16)
2
Recall the Lesson 14 question
In Lesson 14 you wrote functions that modified caller variables through pointers. Ask yourself: where did those caller variables live? Today opens with the natural next question: what if I need memory that has to live past the function that creates it?
3
Skim the In-Class section below
You will see an interactive memalloc walkthrough widget. No need to use it yet; just know it is there and what it looks like.
4. Lesson Materials and Overview

Today is the last new content lesson before GR2. You learn how to ask the operating system for memory yourself, why every allocation must be matched by exactly one free, and how to keep track of who owns what so you do not leak memory, free the same block twice, or read freed memory.

Jump to
Slides Two Regions The Pattern Choosing Ownership DFCS Standard

Slides

The Lesson 15 deck covers stack vs heap, the four allocation functions from the standard library, the ask/check/use/return pattern, the decision table for choosing between stack and heap, and the ownership reasoning framework you will apply in the lab.

Open Lesson 15 slides →

Two memory regions

Every C program uses two regions of memory. The stack is managed by the compiler: every function call gets a frame, and that frame disappears when the function returns. Local variables live there. The heap is managed by you: you call malloc to ask the operating system for memory, the OS gives you a pointer, and the block stays valid until you call free.

The heap is not slower or worse than the stack; it is different. Each region has its own rules and its own use cases. Most programs use both.

The malloc/free pattern

You will write this pattern hundreds of times in the rest of the course. Four steps: ask, check, use, return.

int *plays = malloc(sizeof(int) * 50); // ASK if (plays == NULL) { // CHECK fprintf(stderr, "out of memory\n"); exit(1); } plays[0] = 42; // USE plays[1] = 7; free(plays); // RETURN plays = NULL;

The NULL check is not optional. malloc returns NULL when allocation fails; if you skip the check and try to dereference, your program crashes. Setting the pointer to NULL after free is a defensive habit; if any later code accidentally uses the pointer, the segfault is loud and immediate instead of quiet and corrupting.

Stack or heap?

Two questions usually decide for you.

Question Stack Heap
Is the size known at compile time? Yes No or maybe
Does the data outlive the function? No Yes
Is the data small? Yes (a few KB) Any size
Do I want to manage it myself? No Yes

Ownership: the three questions

For every malloc your program does, answer these three questions out loud (or in a comment):

  1. Who allocated it? Which function called malloc?
  2. Who is responsible for freeing it? The caller? This function? Someone further up?
  3. When is it safe to free? After every reader is done with it. Not before.

The four ownership markers from the slide deck name the answers in code:

Marker Where it goes
// owns: above a function that returns heap memory
// borrows: above a function that takes a pointer but does not free
// alloc owner: next to every malloc/calloc call
// free owner: next to every free call

You will apply these markers in Part B of today's lab.

DFCS C Programming Standard

Today's lesson introduces §8.5 of the DFCS C Programming Standard: always free dynamically allocated memory. The ownership annotation convention you use in Part B is one practical way to follow this rule: if every allocation has a named owner and every owner has a corresponding free, you do not leak. See the Resources section for the full standard. Lesson 19 will revisit §8.5 when struct members are themselves heap pointers.

5. In-Class Work

Two things to do in class. Use the checklist to track your progress.

  • Work through the memalloc walkthrough below. Twelve guided tasks covering stack frames, malloc, calloc, free, and the start of ownership reasoning. About 15 minutes.
  • Complete Lab 15. Two parts in the same repo. Part A: implement make_play_counts and tally_plays and write your own tests in test_lab15.c. Part B: add the four ownership markers to annotate1.c, annotate2.c, and annotate3.c. The full spec is in the repo README.

memalloc Walkthrough

Twelve tasks across four sections. Type each C statement at the prompt. The terminal shows what memalloc did; the middle pane shows the current stack; the right pane shows the heap.

Before you begin

Enter your name. It will appear on the completion screen so you can include it in your screenshot for the Lesson 15 reflection.

CS210 Lesson 15 · memalloc Walkthrough

A guided tour through stack frames, malloc, free, and ownership. Type each C statement on the input line. Watch the stack and heap update with every step.
Task 0 of 12
Section 1: Stack basics
Current task
Loading...
Stack (top is current frame)
No frames yet.
Heap
No allocations yet.
memalloc>
How this works: This is a teaching tool, not a real C interpreter. It accepts a small subset of C plus two extra commands: enter_function name and leave_function to simulate scope changes. The task card tells you what to type next. Mistype twice and the hint button will pulse.
6. After Class
  • Finish Lab 15 (both parts) if you did not complete it in class. Submit through GitHub Classroom before Lesson 16.
  • Complete the Lesson 15 reflection on Blackboard: enter your widget completion code and answer the short reflection prompt.
  • Read Beej-C Chapter 12 again if anything from today is still fuzzy. Tomorrow we cover what goes wrong with what we did today.
  • Heads up: GR2 is at Lesson 17 and covers everything through Lesson 16.
Need help? Schedule EI with your instructor. Bring specific code or specific memalloc screenshots, and the exact error message or output you do not understand. Specific questions get unstuck quickly. Check the Resources section first for references on Git, the toolchain, and common compiler errors.