Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a dangling reference? [duplicate]

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?

like image 901
Jayesh Avatar asked Sep 02 '17 07:09

Jayesh


People also ask

What is a dangling reference?

A link or pointer to an instruction, table element, index item, etc. that no longer contains the same content. If the reference is not a currently valid address, or if it is valid but there is no content in that location, it may cause the computer to crash if the software is not programmed carefully.

How is dangling reference addressed?

Sometimes the programmer fails to initialize the pointer with a valid address, then this type of initialized pointer is known as a dangling pointer in C. Dangling pointer occurs at the time of the object destruction when the object is deleted or de-allocated from memory without modifying the value of the pointer.

What is dangling pointer with example?

The pointers pointing to a deallocated memory block are known as Dangling Pointers. This condition generates an error known as Dangling Pointer Problem. Dangling Pointer occurs when a pointer pointing to a variable goes out of scope or when an object/variable's memory gets deallocated.

What do you mean by dangling pointer and memory leakage?

In other word we can say a pointer whose pointing object has been deleted is called dangling pointer. Memory Leak. In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations.


1 Answers

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.

like image 81
Destructor Avatar answered Oct 08 '22 04:10

Destructor