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

What is class in c++ with example?

783


Please explain the reference variable in c++?

797


Discuss the possibilities related to the termination of a program before entering the mainq method?

733


How can we access protected and private members of a class?

838


Incase of a function declaration, what is extern means?

722


Reads in the size of a square from the screen; 2. Prints a hollow square of that size out of “-“, “|” and blanks on screen; 3. Prints the same hollow square onto a text file. Your program should work for squares of all side sizes between 1 and 20. --- │ │ │ │ │ │ ---

1856


What is an adjust field format flag?

872


How can you quickly find the number of elements stored in a dynamic array? Why is it difficult to store linked list in an array?

769


What is pair in c++?

801


What is c++ map?

754


How do you differentiate between overloading the prefix and postfix increments?

806


When does a 'this' pointer get created?

821


What are the manipulators in c++?

775


how to connect with oracle 9i with server in socket program in c/c++

2080


What are the basic data types used in c++?

764