What is dangling pointers?and what is memory leak?

Answer Posted / kush

a dangling pointer is a pointer which points to a dead location in memory, means the variable or object is exist on that memory location bt that was deleted and pointer is still pointing to that location . this pointer is called dangling pointer.

EX:
int *function()
{
int a=500;
return &a;
}

int main()
{
int *ptr;
ptr=function();
++*ptr;
printf("%d",*ptr);//output=501
}
in the above example one function is there which is having return type int * means this function retuns a address.
now came int main(), i have creating one pointer *ptr and after that calling the function then whatever the address return by function is stored in *ptr.
but see the storage class of variable a in function it is auto by default and when function execution is end that variable is destroyed and funtion will return the address of variable a.
tha variable is destroy bt my *ptr is still pointing and utilizing that meroy location and data on that location this is called dangling pointer..

thanks...

Is This Answer Correct ?    28 Yes 5 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Is c the same as c++?

650


What is a manipulator in c++?

795


Can we use pointers in c++?

696


What is c++ in english?

653


what is COPY CONSTRUCTOR and what is it used for?

712






What is the difference between global variables and static varables?

675


What is null pointer and void pointer?

711


Am studying basic c++ programming, have been given the following assignment. Design a linear program to calculate the maximum stress a material can withstand given a force and a diameter of a circle. To find the required area pi should be defined. Have most of the program sorted out but am at a loss as to how to show the calculations required. Can anyone help?

1831


What do you mean by storage classes?

928


Why is c++ still used?

697


Do we have to use initialization list in spite of the assignment in constructors?

670


why is c++ called oops? Explain

668


What is an adaptor class in c++?

698


What is auto type c++?

723


Which programming language is best to learn first?

684