✏️ Explanatory Question
#include<stdio.h>
void main()
{
int *ptr = malloc(constant value); //allocating a memory space.
free(ptr); //ptr becomes a dangling pointer.
}
In the above example, initially memory is allocated to the pointer variable ptr, and then the memory is deallocated from the pointer variable. Now, pointer variable, i.e., ptr becomes a dangling pointer.
How to overcome the problem of a dangling pointer
The problem of a dangling pointer can be overcome by assigning a NULL value to the dangling pointer. Let's understand this through an example:
#include<stdio.h>
void main()
{
int *ptr = malloc(constant value); //allocating a memory space.
free(ptr); //ptr becomes a dangling pointer.
ptr=NULL; //Now, ptr is no longer a dangling pointer.
}
In the above example, after deallocating the memory from a pointer variable, ptr is assigned to a NULL value. This means that ptr does not point to any memory location. Therefore, it is no longer a dangling pointer.