ProblemsUB & Gotchasreserve() is not resize()
IntermediateUB & Gotchas

reserve() is not resize()

Context

A colleague read '10 C++ optimization tips' and swapped resize for reserve — 'it's faster'. The function now returns an empty vector, but very quickly. The sanitizer lights up red: writes past the size. Explain the difference between capacity and size to him — in code.

Task

firstSquares calls reserve(n) and then writes through v[i] — but reserve only allocates capacity; the vector's size stays 0, so every v[i] is an out-of-bounds write (undefined behaviour) and the function returns an empty vector. Fix the growth.

Constraints

  • Actually grow the vector: use push_back/emplace_back or resize — not bare v[i] after reserve
  • The returned vector has exactly n elements: v[i] == i*i
  • n == 0 returns an empty vector
  • Keeping reserve(n) before push_back is encouraged (one allocation), just not required

Before you code

  • What is the difference between a vector's size and its capacity?
  • Why does v[i] not bounds-check, and what would v.at(i) do here instead?
  • Why does this bug often go unnoticed until much later in the program?

Tests

  • #1Returns n squares
  • #2n = 0 yields an empty vector

Hints

Hint 1

reserve changes capacity; only resize/push_back change size. v[i] requires i < v.size().

Hint 2

Keep the reserve(n) and replace v[i] = … with v.push_back(i * i).

Editorreserve-vs-resize.cpp
Results

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