---
title: Debugging with breakpoints and stepping
heading: Stopping the program to look inside it
eyebrow: C12 · Lesson 9 · Debugging with breakpoints and stepping
xp: 40
---

::: hook
When a program on a microcontroller misbehaves, there's often no screen to print to, and printing changes the timing anyway. A **debugger** stops the processor instead: at a **breakpoint**, or one line at a time, and shows the registers, the variables and memory exactly as they are at that instant. Firmware engineers spend much of their time here. The method that works is the scientific one: form a guess about what's wrong, predict what a variable should hold at some line, stop there, and look.
:::

::: play
- This program should print the average of eight ADC samples, about 510, but prints 8010. Press Run to see it.
- Press Debug. Click the line number of `sum += samples[i];` to set a breakpoint (it lights), then press Continue: the program stops there. Continue again and watch `i` and `sum` in the variables panel.
- When `i` reaches 8, look at what `samples[8]` reads. The array has elements 0 to 7, so element 8 is whatever the linker put next in memory: here, `marker`. Fix the loop and run it again.
:::
:::

```sim board
lang: c
run: 10 ms
show: debug
code:
#include "board.h"

uint16_t samples[8] = {512, 530, 498, 505, 520, 515, 490, 510};
uint16_t marker = 60000;          // the next thing in memory

int main(void) {
    uint32_t sum = 0;
    for (int i = 0; i <= 8; i++)  // a bug hides in this line
        sum += samples[i];
    uint32_t average = sum / 8;
    print(average);
    return 0;
}
```

::: predict
## A breakpoint sits on a line inside a loop that runs 25 times, nested inside a loop that runs 4 times. How many times does Continue stop there?

- [ ] 4
- [ ] 25
- [ ] 29
- [x] 100

::: reveal
100: the inner line runs 25 times on each of the 4 outer passes. That's why debuggers offer **conditional breakpoints**, which stop only when an expression is true, such as `i == 24`.
:::
:::

::: nameit
## What a debugger can do

- **Breakpoint:** stop when execution reaches a line (or an address). Hardware debuggers on real chips have a few hardware breakpoints, often 2 to 8, because they compare the PC in silicon.
- **Step:** run one line (stepping *into* a function call it makes) or one instruction, then stop.
- **Continue:** run until the next breakpoint.
- **Watch:** read variables, registers and memory at the stop. A **watchpoint** stops when a memory location is written, which catches the line that corrupts a variable.

On real hardware this works through a debug port (JTAG or SWD) connected to a probe; the chip's debug logic halts the CPU, and the probe reads its state.

## Debugging well

1. Reproduce the bug reliably.
2. Guess where it starts, and predict what a variable should hold there.
3. Stop there and compare. If the value is already wrong, move earlier; if right, later.
4. Fix the cause, then rerun the failing case.

Common firmware bugs: an index one past the end of an array; a missing `volatile`; the wrong bit in a mask or shift; integer overflow; a variable changed by an interrupt halfway through being used; the stack growing into other data.

## Printing

Printing (`print`, or text on a UART) is simple and works everywhere, but it costs time (a UART at 115,200 baud takes 87 µs per character), so it can hide or create timing bugs.
:::

::: example
## `samples` is an array of `uint16_t` starting at 0x1000. What address does `samples[8]` read?

::: solution
1. **Where element i sits.** Each element is 2 bytes, so element i is at
   $$\text{0x1000} + 2i$$
2. **Element 8.**
   $$\text{0x1000} + 16 = \text{0x1010}$$
3. **What lives there.** That's the first byte past the array, where `marker` lives.

**Answer:** `samples[8]` reads 0x1010, the first byte past the array, where `marker` lives.
:::
:::

::: example
## Printing a 20-character line over a 115,200-baud UART: how long does the program spend, if it waits for each character?

::: solution
1. **Bits per character.** Each character is 10 bits on the wire: a start bit, 8 data bits and a stop bit.
2. **Time for the line.**
   $$\begin{aligned} t &= \frac{20 \times 10}{115\,200}\ \text{s} \\ &= 1.74\ \text{ms} \end{aligned}$$
3. **Compare with the loop.** In a loop meant to run every millisecond, that print alone breaks the timing.

**Answer:** the program spends 1.74 ms on the line.
:::
:::

::: example
## The debugger's memory view shows the bytes 34 12 00 00 at the address of a `uint32_t`. What value does it hold?

::: solution
1. **Byte order.** The processor is little-endian: the first byte is the least significant.
2. **Assemble the value.** Reading 34 12 00 00 from the last byte back to the first gives
   $$\text{0x00001234} = 4660$$
3. **A classic mistake.** Reading memory dumps byte by byte in the wrong order is one of the classic debugging mistakes.

**Answer:** it holds 0x00001234, which is 4660.
:::
:::

::: check
given: base = 0x1000 | 0x1040 | 0x1200; s = 2 | 4; i = 3 | 8 | 10
base: 16
answer: base + s*i

## An array of {s}-byte elements starts at {base:hex4}. What address does element {i} read, in hex?

::: right
Right. base + {s} × {i} = {answer:hex4}.
:::

::: misses
- [base + i] Each element is {s} bytes wide.
- [any] Not yet. base + size × index.
:::
:::

::: check
given: a = 3 | 4 | 10; b = 8 | 16 | 25
answer: a*b
tolerance: 0

## A breakpoint sits inside a loop of {b} passes, nested in a loop of {a} passes. How many times does it stop the program?

::: right
Right. {answer}.
:::

::: misses
- [a + b] The inner loop runs fully on every outer pass.
- [any] Not yet. Inner passes times outer passes.
:::
:::

::: check
given: n = 10 | 20 | 40; baud = 9600 | 115200
answer: n*10/baud*1000
unit: ms
tolerance: 0.5%

## A program prints {n} characters over a UART at {baud} baud, waiting for each. How long does it take?

::: right
Right. 10 bits per character: {answer} ms.
:::

::: misses
- [n*8/baud*1000] Each character also has a start and a stop bit: 10 bits.
- [any] Not yet. Characters × 10 bits ÷ baud.
:::
:::

::: check
given: n = 8 | 16; m = 60000 | 1000; v = 500 | 512
answer: (n*v + m)/n
tolerance: 0.5%

## A loop meant to average {n} samples, each {v}, runs one pass too many and adds the next value in memory, {m}, before dividing by {n}. What does it compute?

::: right
Right. {answer}, instead of {v}.
:::

::: misses
- [v] That's the right average; the extra value is added in.
- [(n*v + m)/(n + 1)] It still divides by {n}.
- [any] Not yet. $(n v + m)/n$.
:::
:::

::: check
kind: order

## Put the steps of tracking down a bug in order.

1. Make the bug happen reliably
2. Guess where it starts and predict a variable's value there
3. Stop the program there and compare the value with the prediction
4. Move earlier or later depending on whether it was already wrong
5. Fix the cause and rerun the failing case
:::

::: check
kind: choice

## A variable is being corrupted somewhere, but you don't know which line writes to it. Which tool finds that line fastest?

- [ ] A breakpoint at the top of main
- [x] A watchpoint on the variable's address
- [ ] Stepping through the whole program one instruction at a time
- [ ] Printing the variable at the end

::: misses
- [1] That stops once, before anything goes wrong.
- [3] It would work, eventually; a watchpoint does it in one Continue.
- [4] That shows it's wrong, but not where it went wrong.
:::
:::

::: check
kind: c
run: 0.01
expect: print = 510

## Fix the averaging program from the play so it prints the true average of its eight samples, 510.

```c starter
#include "board.h"

uint16_t samples[8] = {512, 530, 498, 505, 520, 515, 490, 510};
uint16_t marker = 60000;

int main(void) {
    uint32_t sum = 0;
    for (int i = 0; i <= 8; i++)
        sum += samples[i];
    uint32_t average = sum / 8;
    print(average);
    return 0;
}
```

```c solution
#include "board.h"

uint16_t samples[8] = {512, 530, 498, 505, 520, 515, 490, 510};
uint16_t marker = 60000;

int main(void) {
    uint32_t sum = 0;
    for (int i = 0; i < 8; i++)
        sum += samples[i];
    uint32_t average = sum / 8;
    print(average);
    return 0;
}
```

::: right
Right: `i < 8` stops after element 7.
:::
:::

::: check
kind: micropython
run: 0.01
expect: print = 21

## This program should print the largest of its readings, 21, but prints 13. Find the bug (print values along the way if that helps) and fix it.

```micropython starter
readings = [21, -3, 7, 13, 9]
largest = 0
for i in range(1, len(readings)):
    if readings[i] > largest:
        largest = readings[i]
print(largest)
```

```micropython solution
readings = [21, -3, 7, 13, 9]
largest = readings[0]
for i in range(1, len(readings)):
    if readings[i] > largest:
        largest = readings[i]
print(largest)
```

::: right
Right. The loop starts at index 1, so the largest-so-far has to start as reading 0, not as 0 (which would also fail if every reading were negative).
:::
:::

::: check
kind: parts
given: B = 4096 | 8192; i = 3 | 9 | 27; s = 2 | 4 | 8

## An array of {s}-byte elements starts at {B}.

::: part
answer: B + i*s
tolerance: 0

### What address does element {i} occupy?

::: misses
- [B + i] Multiply by the element size.
- [any] base + i × size.
:::
:::

::: part
answer: s
tolerance: 0

### How many bytes does the debugger's memory view show for one element?

::: misses
- [any] The element size.
:::
:::
:::

::: check
kind: parts
given: n = 10 | 40 | 120; b = 9600 | 115200

## A program prints a {n}-character line over a {b}-baud UART and waits for each character.

::: part
answer: n*10/b*1000
unit: ms
tolerance: 0.5%

### How long does it spend printing?

::: misses
- [n*8/b*1000] Each character is 10 bits on the wire with start and stop.
- [any] 10 bit-times per character.
:::
:::

::: part
answer: n*10/b*1e7
tolerance: 0.5%

### How many 10 MHz cycles is that?

::: misses
- [any] Time × 10 MHz.
:::
:::
:::

::: explain
## Why is stopping at a breakpoint often better than adding prints to find a bug in firmware?

::: model
A breakpoint shows everything at once (every variable, register and memory location) at the exact instant chosen, without deciding in advance what to print, and it can be moved and the program rerun without editing the code. Printing changes the program: each print takes time (milliseconds over a UART), which shifts timing and can make a timing bug appear or disappear, and it needs a working output channel. Prints are still useful for watching a program run at full speed over a long time, where stopping it would break what's being observed.
:::
:::

::: practice

::: check
given: base = 0x1000 | 0x1100; s = 2 | 4; i = 5 | 12
base: 16
answer: base + s*i

## Address of element {i} of {s}-byte elements at {base:hex4}?

::: misses
- [any] base + s × i.
:::
:::

::: check
given: a = 5 | 7; b = 12 | 20
answer: a*b
tolerance: 0

## Stops for a breakpoint in a {b}-pass loop inside a {a}-pass loop?

::: misses
- [any] a × b.
:::
:::

::: check
given: n = 32 | 64; baud = 9600 | 57600
answer: n*10/baud*1000
unit: ms
tolerance: 0.5%

## Time to print {n} characters at {baud} baud?

::: misses
- [any] n × 10 / baud.
:::
:::
:::
