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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With