Lesson 05
Stack, Heap and Memory
Goal
By the end of this lesson you will be able to:
-
Say what the stack is and what the heap is.
-
Draw the stack as variables are declared and as a block ends.
-
Decide whether a piece of data goes on the stack or on the heap, and say why.
-
Predict what an assignment copies, and how many copies of the data exist afterwards.
-
Draw the stack frames of a run of function calls.
-
Work out the address of every variable on the stack by hand.
There is no code in this lesson. Every drill is answered with a pencil, and every drill has one correct answer you can check against.
Two Places for Data
A running program keeps its data in two places. They work in different ways, and almost every rule you will meet later comes from the difference.
The Stack
The stack is a pile. A new variable is put on the top. When the program leaves the block the variable was declared in, it is taken off the top again.
Nothing is ever taken out of the middle. The variable put on last is the one taken off first. This is called LIFO, short for last in, first out. A pile of plates behaves the same way: you take the plate you put down most recently.
The stack is fast, because putting a value on it is just moving the top marker. It has one condition. Every value on the stack must have a size the compiler already knows, before the program runs.
The Heap
The heap is a large area the program asks memory from while it runs. You use it when the size is not known in advance, or when the size changes as the program runs. Text typed in by the user is the clearest example: you cannot know how long it will be until it arrives.
Asking for heap memory is slower than putting a value on the stack. The memory also stays reserved until somebody gives it back.
Comparing the Two
| Stack | |
|---|---|
| Size must be known | when the program is compiled |
| Order | last in, first out |
| Speed | fast |
| Cleared | automatically, at the end of the block |
| Heap | |
|---|---|
| Size must be known | only while the program runs |
| Order | any order |
| Speed | slower |
| Cleared | when somebody gives the memory back |
Heap Data Still Has a Stack Record
A value that lives on the heap is not reached out of thin air. The variable itself still sits on the stack. What it holds is a small, fixed-size record that describes the heap data:
| Field | Size | What it holds |
|---|---|---|
| pointer | 8 bytes | the address of the data on the heap |
| length | 8 bytes | how many items are in use right now |
| capacity | 8 bytes | how many items there is room for |
That record is 24 bytes, and it is 24 bytes whether the heap holds three characters or three million. The size of the record is known when the program is compiled, which is exactly why it is allowed on the stack.
The Rule Behind Everything Here
The size decides the place. If the compiler can work out the size before the program runs, the value goes on the stack. If the size is only known while the program runs, or can change while it runs, the data goes on the heap, and a fixed-size record on the stack points at it.
How the Drills Are Drawn
Every drill in this lesson uses the same convention, so that each one has a single correct answer:
-
The stack starts at address 1000, unless the drill says otherwise.
-
The first variable declared takes the lowest addresses. The next one starts at the byte straight after it. Nothing is left empty between two variables.
-
Addresses are counted in bytes, and the drills use plain decimal numbers.
-
The stack is drawn as a table growing down the page, first variable at the top.
Drill 1: Trace the Stack
You are given a list of declarations in plain English. Draw the stack after each step, and show what is left when a block ends.
Worked Example
| 1. | Declare a, size 4 bytes |
| 2. | Declare b, size 8 bytes |
| 3. | Declare c, size 4 bytes |
| 4. | The block ends |
After step 3 the stack holds all three, in the order they were declared:
| Name | Size | Addresses | |
|---|---|---|---|
a | 4 | 1000 to 1003 | put on first |
b | 8 | 1004 to 1011 | |
c | 4 | 1012 to 1015 | put on last, sits on top |
The stack is 16 bytes tall, and the next free address is 1016.
At step 4 the block ends and all three come off. They come off in the reverse of the order they went on: c first, then b, then a. The next free address goes back to 1000.
Two Answers, Every Time
A trace has two parts. The order the variables go on and come off, and the addresses each one occupies. Write both.
Exercises
For each list, draw the stack at the moment marked, and write the order the variables are removed in.
1. Declare p, 8 bytes. Declare q, 2 bytes. Declare r, 8 bytes. Draw the stack now.
(space to draw your answer)
Removal order: ______
2. Declare n, 4 bytes. Declare m, 1 byte. Declare k, 1 byte. Declare j, 2 bytes. Draw the stack now, and give the next free address.
(space to draw your answer)
Next free address: ______
3. Declare x, 4 bytes. An inner block starts. Declare y, 8 bytes. Declare z, 4 bytes. The inner block ends. Draw the stack straight after the inner block ends.
(space to draw your answer)
Next free address: ______
4. Declare a, 2 bytes. Declare b, 4 bytes. An inner block starts. Declare c, 8 bytes. The inner block ends. Declare d, 4 bytes. Draw the stack at the end, and give the address of d.
(space to draw your answer)
Address of d: ______
5. The stack starts at address 2000 for this one. Declare h, 8 bytes. Declare i, 8 bytes. Declare j, 8 bytes. Draw the stack, then say which variable is removed first and which is removed last.
(space to draw your answer)
Removed first: ______
Removed last: ______
Drill 2: Stack or Heap?
Mark each one stack or heap, then write the reason in one short sentence. The reason is always about the size: is it known when the program is compiled, or only while the program runs?
Where a value keeps a record on the stack and its data on the heap, write both and say which part is where.
Worked Example
| What it is | Where | Why |
|---|---|---|
| A signed 32-bit whole number | stack | Always 4 bytes. The size is known before the program runs. |
| A line of text typed in by the user | both | The length is only known once it is typed. The characters go on the heap; the 24-byte record goes on the stack. |
Exercises
| What it is | Where | Why | |
|---|---|---|---|
| 6. | A bool | ______ | ______ |
| 7. | An i32 | ______ | ______ |
| 8. | A u8 | ______ | ______ |
| 9. | An f64 | ______ | ______ |
| 10. | An array of 4 numbers, the 4 written in the source | ______ | ______ |
| 11. | An array of 1000 numbers, the 1000 written in the source | ______ | ______ |
| 12. | A list that starts empty and grows to 10 items while the program runs | ______ | ______ |
| 13. | A pair of two numbers, both written in the source | ______ | ______ |
| 14. | The whole contents of a file read in while the program runs | ______ | ______ |
| 15. | A fixed piece of text written in the source and never changed | ______ | ______ |
The Trap in Question 11
An array of 1000 numbers is large, but its size is written in the source, so the compiler knows it. Size is the test, not how big the number is. Question 12 is the smaller of the two and still needs the heap, because the count is only settled while the program runs.
Drill 3: What an Assignment Copies
Two variables, and the assignment b = a. Predict what is copied.
There are only two answers, and the shape of a decides which one:
-
ais a fixed-size value sitting on the stack. Every one of its bytes is copied. There are now two separate values, and changing one does not touch the other. -
ais a 24-byte record pointing at data on the heap. Only the 24 bytes of the record are copied. The heap data is not copied. There are now two records, both holding the same address, and one piece of data on the heap.
Worked Example
a is a signed 32-bit whole number, 4 bytes on the stack. b = a copies all 4 bytes. Two values exist afterwards. Writing to b leaves a alone. There is no hazard.
Now a is a line of text: a 24-byte record on the stack, and 11 characters on the heap. b = a copies the 24 bytes of the record only. The 11 characters are not copied. Afterwards two records hold the same heap address.
The Hazard to Name
Two records, one piece of data. If both records are treated as owning the heap data, the memory gets given back twice, and the program corrupts its own memory. If only one is treated as the owner, the other is left pointing at memory that has already been given back. This single problem is the reason ownership exists.
Exercises
For each row give three answers: how many bytes the assignment copies, how many copies of the actual data exist afterwards, and the hazard, if there is one.
16. a is a bool, 1 byte on the stack.
| Bytes copied: | ______ | Copies of the data: | ______ |
Hazard: ______
17. a is an array of 4 numbers, 4 bytes each, all on the stack.
| Bytes copied: | ______ | Copies of the data: | ______ |
Hazard: ______
18. a is a 24-byte record pointing at 5000 bytes of text on the heap.
| Bytes copied: | ______ | Copies of the data: | ______ |
Hazard: ______
19. a is a 24-byte record pointing at 8 bytes of text on the heap.
| Bytes copied: | ______ | Copies of the data: | ______ |
Hazard: ______
20. a is a pair holding one 4-byte number and one 24-byte record that points at the heap.
| Bytes copied: | ______ | Copies of the data: | ______ |
Hazard: ______
Write one sentence on why question 18 and question 19 have the same answer for the first two columns:
(space to draw your answer)
Drill 4: Function Calls on the Stack
Every function call puts a frame on the stack. The frame holds that call’s own variables. When the function returns, its frame comes off, and everything in it is gone.
Frames follow the same last in, first out rule as single variables. A function cannot return before the function it called has returned, so frames always come off in the reverse of the order they went on.
Worked Example
| 1. | main starts |
| 2. | main calls f |
| 3. | f calls g |
| 4. | g returns |
| 5. | f returns |
The stack at each step, with the newest frame at the bottom of the drawing:
| After step | Frames on the stack |
|---|---|
| 1 | main |
| 2 | main, f |
| 3 | main, f, g |
| 4 | main, f |
| 5 | main |
Three frames is the tallest the stack ever gets. g was put on last and came off first.
Exercises
For each run, list the frames on the stack after every step, and write down the greatest number of frames reached.
21. main starts. main calls read. read returns. main calls write. write returns.
(space to draw your answer)
Tallest the stack got: ______
22. main starts. main calls a. a calls b. b calls c. c returns. b returns. a returns.
(space to draw your answer)
Tallest the stack got: ______
23. main starts. main calls setup. setup calls load. load returns. setup calls check. check returns. setup returns.
(space to draw your answer)
Tallest the stack got: ______
24. A function that calls itself. main calls count. That count calls count again. That one calls count a third time. The third one returns, then the second, then the first.
(space to draw your answer)
Tallest the stack got: ______
25. Each frame in question 24 is 32 bytes, and the stack starts at address 1000. main itself uses a 16-byte frame. Give the address the third count frame starts at.
(space to draw your answer)
Address: ______
Why a Runaway Function Crashes
A function that calls itself and never stops keeps adding frames. The stack has a fixed size, so it eventually has no room left and the program stops. Question 24 shows the shape of it: three calls, three frames, and nothing comes off until the innermost call returns.
Drill 5: Working Out Addresses
Given the address the stack starts at and the size of each variable, work out where every variable sits. Each variable starts at the byte straight after the one before it, and nothing is left empty in between.
Worked Example
The stack starts at 1000. The sizes are 4, 1, 8, 2 bytes.
| Name | Size | First byte | Last byte | |
|---|---|---|---|---|
a | 4 | 1000 | 1003 | starts where the stack starts |
b | 1 | 1004 | 1004 | |
c | 8 | 1005 | 1012 | |
d | 2 | 1013 | 1014 |
The last byte of a variable is its first byte plus its size, minus one. A 4-byte variable starting at 1000 ends at , not at 1004. That off-by-one is the mistake to watch for.
Total used: bytes. Next free address: 1015.
Exercises
26. The stack starts at 1000. Sizes: 8, 8, 4.
| Name | Size | First byte | Last byte |
|---|---|---|---|
a | 8 | ______ | ______ |
b | 8 | ______ | ______ |
c | 4 | ______ | ______ |
Next free address: ______
27. The stack starts at 2000. Sizes: 1, 1, 2, 4, 8.
| Name | Size | First byte | Last byte |
|---|---|---|---|
p | 1 | ______ | ______ |
q | 1 | ______ | ______ |
r | 2 | ______ | ______ |
s | 4 | ______ | ______ |
t | 8 | ______ | ______ |
Next free address: ______
28. The stack starts at 5000. Sizes: 24, 4, 24.
| Name | Size | First byte | Last byte |
|---|---|---|---|
one | 24 | ______ | ______ |
two | 4 | ______ | ______ |
three | 24 | ______ | ______ |
Next free address: ______
29. The stack starts at 1000. An array holds 6 numbers of 4 bytes each, and is declared first. A bool is declared after it.
| Name | Size | First byte | Last byte |
|---|---|---|---|
| the array | ______ | ______ | ______ |
the bool | ______ | ______ | ______ |
Address of the array’s fourth number: ______
30. The stack starts at 1000. Declare a, 4 bytes. Declare b, 8 bytes. An inner block starts. Declare c, 4 bytes. The inner block ends. Declare d, 4 bytes.
| Name | Size | First byte | Last byte |
|---|---|---|---|
a | 4 | ______ | ______ |
b | 8 | ______ | ______ |
c | 4 | ______ | ______ |
d | 4 | ______ | ______ |
Which two variables share a first byte, and why?
(space to draw your answer)
Reusing the Space
When a block ends, its variables come off the stack and the space they used is free again. The next variable declared starts there. Two variables that never exist at the same time can sit at the same address, one after the other in time.
Check what stuck
The practice sheet for this lesson has 50 multiple-choice questions. Each one is a short program: pick what it prints, or why it does not compile.
Start practice →