The blog is in holidays for the next couple weeks. In the meantime, here’s a cool debugging story from elsewhere:
Who are you?
What’s the hardest/funniest bug you’ve met and how did you solve it?
I was recently coding a VM for my code club and couldn’t figure out why none of it was working.
A VM (virtual machine) works like a real CPU. It has a pointer to the current instruction being executed. Usually it’s called the program counter (
The VM works by executing one instruction and moving on to the next. So I coded just that. Executing the instruction, done in a big
case loop. And then moving to the next instruction, by incrementing the program counter (instructions are 2 bytes long, so
pc += 2).
However, some of those instructions also play with the
pc. One in particular is used for implementing control flow (think of it as an
if). It would set the
pc to an address in memory. If a condition is
true move the
pc to that address in memory. That’s how all control flow structures are implemented on your CPU.
Here’s the bug. Remember from earlier, I was incrementing the
pc right after executing an instruction. That means each time an
if was executed the VM would jump to a memory address + 2. Two bytes too far.
The solution was to increment the
pc before executing the instruction: https://github.com/greatcodeclub/chip8/blob/master/vm.js#L37.
Anything else to add?
Here’s my process for solving a bug in pseudo machine code.
- Get stuck because of said bug.
- Bang head on keyboard.
- Stop coding and move away from machine.
- Get back to machine and try something new.
- Jump to step 7 if bug solved.
- Jump to step 2.
- Celebrate with a drink.
But usually when I find the bug, it is so dumb and stupid I try hard to forget it to keep my confidence up.
This is when I first learned the horrors of the Mac. While Unix says ‘Im sorry you can’t do that’, MacOS has two error messages.
It either goes ‘eep?’ or the box you wanted to set but couldn’t is simply not there on you computer until you’ve installed the other 12 unidenfied items and filled in 3 apparently unrelated dialog boxes. This was an error of the latter category.