ProblemsUB & GotchasReturn of the dangling reference
NoviceUB & Gotchas

Return of the dangling reference

Context

The senior who left for a startup to 'make it big' left a farewell commit: returning const std::string& instead of by value — 'optimization, fewer copies'. Review was a formality, he's a senior after all. Now user greetings arrive as memory garbage. Fix the signature, then explain at retro why the compiler had been warning all along.

Task

makeGreeting returns a reference to a local variable — the string dies when the function returns, and the caller is left holding a dangling reference (undefined behaviour). Fix the signature so the caller receives a valid string.

Constraints

  • makeGreeting must return the string by value (no reference into the dead frame)
  • The returned string must be valid and correct after the call
  • Keep building the greeting inside the function (no globals/statics as a workaround)

Before you code

  • What exactly happens to s when makeGreeting returns?
  • Why is returning by value cheap here anyway? (NRVO / move semantics)
  • Why is a static local a poor "fix" for this bug?

Tests

  • #1Greeting is valid after the call
  • #2Two calls produce independent strings

Hints

Hint 1

The fix is one character class: change the return type from const std::string& to std::string.

Hint 2

Returning a local by value is cheap: the compiler elides the copy (NRVO) or moves it.

Editordangling-reference.cpp
Results

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