Dangling Pointer in C
- The pointer variable which is pointing to a inactive or dead location is called dangling pointer.
- When A pointer pointing to non-existing memory location is called dangling pointer.
Examples of dangling pointer
int * abc()
{
int a=10;
–a;
return &a;
}
void main()
{
int *ptr;
ptr=abc();
printf(“value of a =%d,*ptr);
}
output : = 9 //this is illegal
- in Previous Program, ptr is called dangling pointer because according to storage class of C by default any type of variable storage class specifier is void and lifetime of auto variable is within the body only but in previous program control is passing back to main function it is destroyed but sill pointer is pointing to that inactive variable only.
Solution of dangling pointer
- Solution of dangling pointer in place of creating auto variable recommended to create static variable because lifetime of static variable is entire program.
Example to avoid dangling pointer:-
ex:-
int *abc()
{
static int s=10;
–s;
return &s;
}
void main()
{
int * ptr;
ptr=abc();
printf(“ststic data:%d”,*ptr)
}