ProblemsUB & GotchasThe off-by-one that reads past the end
NoviceUB & Gotchas

The off-by-one that reads past the end

Context

The nightly batch sums arrays and occasionally delivers one addend more than ordered. That 'occasionally' depends on what happens to live in the heap right past the array — delightful to debug. The <= n loop reads a[n], an element that doesn't exist. Off-by-one: the cheapest bug by characters, the most expensive by consequences.

Task

sumArray walks one element too far: its loop condition reads a[n], one past the last valid index. That is a heap buffer over-read — undefined behaviour. Fix the bounds so it sums exactly the n elements.

Constraints

  • Must sum exactly a[0] .. a[n-1] — never read a[n]
  • Must be clean under AddressSanitizer (no out-of-bounds read)
  • Keep the same signature and return the correct sum
  • An n of 0 returns 0 and reads nothing

Before you code

  • Why is reading a[n] (one past the end) undefined behaviour, not just "reading a stray value"?
  • What is the valid index range for an array of length n?
  • How would AddressSanitizer report this, and why only sometimes a crash without it?

Tests

  • #1Sums a heap array without over-reading
  • #2Zero length reads nothing
  • #3Sums a small array

Hints

Hint 1

Valid indices are 0 .. n-1. The loop condition should be i < n, not i <= n.

Editorfix-the-buffer-overflow.cpp
Results

Hit Submit (or ⌘/Ctrl + ↵) — test results will show up here.