What is dangling pointer in C?

Long Answer
Views 577

Answer:

  • 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.


#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.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of C Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.