ProblemsUB & GotchasThe pointer that dangles
IntermediateUB & Gotchas

The pointer that dangles

Context

The tag service kept a pointer to a vector element 'for speed'. The vector grew, moved to new memory, and the pointer stayed loyal to the old address. The crash, naturally, fired three modules away from the bug. Stop caching addresses into someone else's storage — the vector has no sentimentality about it.

Task

sumOfFirst caches a pointer to a vector's first element, then keeps push_back-ing into the same vector. When the vector reallocates, that pointer dangles — reading it is a heap use-after-free. Fix the function so it stays correct (and ASan-clean).

Constraints

  • Must return v[0] added once per appended element — i.e. v[0] * count using the original first value
  • Must not read through a pointer/reference/iterator that a push_back may have invalidated (ASan must stay clean)
  • Keep appending the count values 0..count-1 to v as a side effect
  • Do not cache the address of an element across a push_back

Before you code

  • Which operations invalidate iterators/pointers/references into a std::vector?
  • Why does reserve help, and when is it still not enough?
  • What is the safest way to refer to "the first element" across mutations — an index or an address?

Tests

  • #1Correct sum, ASan-clean
  • #2Appends the expected values
  • #3Zero appends leaves the vector unchanged

Hints

Hint 1

Read the value once before the loop: int firstVal = v[0]; — a copy can never dangle.

Hint 2

If you truly need the live first element, index it fresh each time (v[0]) instead of caching its address.

Editorfix-the-invalidation.cpp
Results

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