ProAnswers.org

What is a dangling pointer in c?

A dangling pointer arises when you use the address of an object after its lifetime is over. This may occur in situations like returning addresses of the automatic variables from a function or using the address of the memory block after it is freed.

a pointer whose pointing object has been deleted is called dangling pointer.

look at this code:

int *call();
void main(){
int *ptr;
ptr=call();
clrscr();
printf("%d",*ptr);

}
int * call(){
int x=25;
++x;
return &x;
}

o/p: Garbage value

variable x is local variable. Its scope and lifetime is within the function call hence after returning address of x variable x became dead and pointer is still pointing ptr is still pointing to that location.

by Making the variable x as static variable we can solve this problem.