What you learn today
- StackOverFlow and StackUnderFlow
- Overwriting sp by accident
- Memory after a restart
A chip has been running flawlessly for hours, then it suddenly stops with StackOverFlow. Nobody changed anything. The bug was in the code from the start, it just needed 512 ticks to show.
StackOverFlow and StackUnderFlow
| Error | cause |
|---|---|
StackOverFlow | push at sp = 512 or an address above 511 |
StackUnderFlow | pop or peek at sp = 0 or a negative address |
The classic case: one pass puts three values onto the stack but only takes two off. Every tick sp grows by one. After a little over 500 ticks, a little over four minutes, the stack is full.
push a
push b
push c
pop x
pop y # the third pop is missing: sp grows every tick
The rule: in every pass as many pop as push. If you are unsure, put move sp 0 at the start of the main loop. Then every pass begins with an empty pile, even if a pop is missing somewhere.
Overwriting sp by accident
sp is a perfectly normal register, number 16. Every instruction that writes into it moves the pile: move sp 7, add sp sp 1, an alias on r16. Afterwards pop reads from a wrong place, without an error message. A register plan with alias only for r0 to r15 protects against that.
Memory after a restart
In the game code, uploading new code and re-inserting the chip only set sp and the program line to 0. Registers and stack contents stay. They are stored in the save as well.
For the stack that means: after a restart sp is 0, but the addresses still hold the old values. A table you fill with poke is back immediately. A counter you keep in an address carries on with the old value. If you want a clean start, clear with clr db before the start label.
The simulator on this site starts every test with an empty stack and zeros in all registers. A bug that only appears with old values therefore only shows in the game.
An overflow after hours is quick to find in the simulator: speed on “Full throttle” and keep an eye on the stack pointer. If sp grows from tick to tick, a pop is missing somewhere.
Diagram
Exercise
Task
The chip in the editor looks for the highest temperature of the gas sensors “Nord”, “Mitte” and “Sued” via the stack. It has a bug that stops it with StackOverFlow after a while, and it overlooks one sensor.
- Find and fix the bug so that every pass leaves the stack empty again (
sp= 0). - LED “Hoechst” shows the highest of the three temperatures in °C.
- If a sensor is missing, the display shows −999.
Hints
Hint 1
Count the push and the pop in one pass.
Hint 2
The missing pop fetches the value of “Nord” – then one more max.
Hint 3
max with NaN gives NaN. One snan on the result is enough for the −999.
Quiz
4 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed the simulator exercise
- Passed the quiz with at least 60 %
Without an account progress is saved in this browser only.
Report a mistake in this lesson
Please sign in to report. Sign in