17

Following program give me runtime error(Segmentation Fault (SIGSEGV)).

#include <iostream>
using namespace std;

int& bar()
{
    int n = 10;
    return n;
}

int main() {
    int& i = bar();
    cout<<i<<endl;
    return 0;
}

My teacher told me it is a undefined behavior because dangling reference. Is he right? If yes then how to avoid it?

Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • There's gotta be a good duplicate for this. – hyde Sep 02 '17 at 07:28
  • Yes, your computer is right when it complains about computer stuff. So, what **is** the exact error? Copy and paste the error message into your question. And I'm not sure you get a *runtime* error; your compiler should already be warning you. – Marcus Müller Sep 02 '17 at 07:28
  • 1
    @KillerDeath `endl` is for new line formatting in `cout` – Suraj Rao Sep 02 '17 at 07:29
  • 5
    @tkausl I asked about "Dangling reference" . Not "Dangling Pointer". Pointer and reference are different things. – Jayesh Sep 02 '17 at 07:32
  • 3
    In short, you return reference to local variable of function. When function returns, local variable ceases to exist, and the returned reference becomes dangling: it does not reference a valid variable. Solution: return value, not reference, or allocate object from heap and return a (smart) pointer. – hyde Sep 02 '17 at 07:33
  • I know, but the answers in the other question are equally true for references. – tkausl Sep 02 '17 at 07:34
  • Marked as duplicate, since there is a distinct relationship between a pointer and a reference that refer to the same object. A dangling reference is a reference to an object that does not exist, or no longer exists. A dangling pointer is a pointer to an object that does not exist, or no longer exists. Dereferencing a dangling pointer (e.g. `*dangling_p`) produces a dangling reference. Computing the address of (the object referenced by) a dangling reference (i.e. `&dangling_reference`) produces a dangling pointer. – Peter Sep 02 '17 at 07:55
  • 3
    Duping "dangling reference" to "dangling pointer" is not incorrect from an academic perspective, but seems rather unhelpful. Even though most answers apply roughly also to references, I don't think it actually helps anyone who doesn't already understand pointers, references and their dangling counterparts pretty well. – Daniel Roethlisberger Nov 17 '20 at 10:22

1 Answers1

14

Yes it is indeed an undefined behavior because you are returning a reference to automatic variable which will be destroyed when execution of bar() completes

You can avoid it by writing:

#include <iostream>
using namespace std;

int& bar()
{
    static int n = 10;
    return n;
}

int main() {
    int& i = bar();
    cout<<i<<endl;
    return 0;
}

In this case static variable n will not be destroyed when execution of bar() completes, it will be destroyed when your program terminates.

Destructor
  • 14,123
  • 11
  • 61
  • 126