← Exercises|

Debug: one step too far

Debug13 of 14 · about 6 min

Debug: one step too far

An array of n elements has indexes 0 to n-1. a[n] is one past the last one, and C will happily let you write there. Nothing checks it.

The off-by-one comes from writing <= where < was meant, and it is close to universal — it is worth reading every loop condition you write once, specifically for this.

The runtime here stops at the exact write and names the array and the offset. Learn what that report looks like: it is the same information AddressSanitizer gives you on the real thing.

Example

int a[5];
for (int i = 0; i < 5; i++) { /* 0,1,2,3,4 — right */ }
for (int i = 0; i <= 5; i++) { /* 0,1,2,3,4,5 — the last one is past the end */ }

Your task

This is meant to reverse an array in place. Run it, read the failure, and fix it. There are two problems.

Stuck?

Explain it

Why is a[n - i] wrong when i is 0, in a way that a[n - 1 - i] is not?

Not graded — this is for you.

Where this goes

Project 7 asks you to build and test array operations including a reverse. This is the bug its tests are designed to catch.