Skip to main content
C++ Bug Hunt Medium +20 XP

Dangling Reference

This function returns a dangerous reference.

C++Find the bug
1int& getRef() {
2 int x = 42;
3 return x;
4}
The bug is on line 3

Select the correct fix

Show answer and explanation

Answer: Return by value instead of reference

x is a local variable destroyed when the function returns. Returning a reference to it creates a dangling reference.

Hint: What happens to local variables after a function returns?

What this challenge tests

Bug Hunt in C++: references, lifetime, dangling.

Related challenges