ProblemsUB & GotchasThe uninitialized accumulator
NoviceUB & Gotchas

The uninitialized accumulator

Context

The board report shows $2.4M revenue in the debug build and $-9.18e18 in release. The CFO chose to believe the first number; engineering chose to find the bug. The culprit: int total; uninitialized. Debug zeroes the stack out of kindness; release serves whatever was lying there. Initialize it and never do that again.

Task

sumPositive starts adding into a variable that was never initialized — reading an indeterminate value is undefined behaviour, and the "sum" is garbage plus your numbers. Initialize the accumulator.

Constraints

  • The accumulator must be initialized before any read
  • sumPositive of an empty vector returns exactly 0
  • Only strictly positive elements are added
  • Keep the signature unchanged

Before you code

  • Why does the buggy version often appear to work in debug builds?
  • What does the C++ standard say about reading an uninitialized int?
  • Which compiler warning catches this, and at which -W level?

Tests

  • #1Sums only the positive elements
  • #2Empty vector returns exactly 0
  • #3All-negative vector returns 0

Hints

Hint 1

int total = 0; — that is the whole fix. The interesting part is understanding why the original is UB, not just "wrong".

Editoruninitialized-accumulator.cpp
Results

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