What is dangling pointer in C?

    • If a pointer is pointing any memory location, but meanwhile another pointer deletes the memory occupied by the first pointer while the first pointer still points to that memory location, the first pointer will be known as a dangling pointer. This problem is known as a dangling pointer problem.
    • Dangling pointer arises when an object is deleted without modifying the value of the pointer. The pointer points to the deallocated memory.

    Let’s see this through an example.

    1. #include<stdio.h>
    2. void main()
    3. {
    4.         int *ptr = malloc(constant value); //allocating a memory space.
    5.         free(ptr); //ptr becomes a dangling pointer.
    6. }

    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:

    1. #include<stdio.h>
    2.       void main()
    3.       {
    4.               int *ptr = malloc(constant value); //allocating a memory space.
    5.               free(ptr); //ptr becomes a dangling pointer.
    6.               ptr=NULL; //Now, ptr is no longer a dangling pointer.
    7.       }

    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.