Dangling Pointer
It is a pointer which points to some non-existing memory location. When we free the memory that is pointing to the pointer that is allocated memory dynamically, the pointer still contains the address of first byte of released memory. Hence it is known as Dangling Pointer.
#include<stdio.h>
#include<stdlib.h>
void main()
{
int *ptr=(int *)malloc(8);
*ptr=2;
*(ptr+1)=4;
printf(“nptr=%d”,ptr);
printf(“n*ptr=%d”,*ptr);
printf(“n*(ptr+1)=%d”,*(ptr+1));
free(ptr);
printf(“nnAfter releasing memory:”);
printf(“nptr=%d”,ptr);
printf(“n*ptr=%d”,*ptr);
printf(“n*(ptr+1)=%d”,*(ptr+1));
}
Solution of Dangling Pointer is assign the pointer will NULL value after releasing memory.
#include<stdio.h>
int *fun()
{
int num=10;
return #
}
void main()
{
int* ptr;
ptr=fun();
printf(“%d”,ptr);
printf(“n%d”,*ptr);
}